es6.js 4.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559
  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. "use strict";
  4. var BABYLON;
  5. (function (BABYLON) {
  6. /**
  7. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  8. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  9. */
  10. var EffectFallbacks = /** @class */ (function () {
  11. function EffectFallbacks() {
  12. this._defines = {};
  13. this._currentRank = 32;
  14. this._maxRank = -1;
  15. }
  16. /**
  17. * Removes the fallback from the bound mesh.
  18. */
  19. EffectFallbacks.prototype.unBindMesh = function () {
  20. this._mesh = null;
  21. };
  22. /**
  23. * Adds a fallback on the specified property.
  24. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  25. * @param define The name of the define in the shader
  26. */
  27. EffectFallbacks.prototype.addFallback = function (rank, define) {
  28. if (!this._defines[rank]) {
  29. if (rank < this._currentRank) {
  30. this._currentRank = rank;
  31. }
  32. if (rank > this._maxRank) {
  33. this._maxRank = rank;
  34. }
  35. this._defines[rank] = new Array();
  36. }
  37. this._defines[rank].push(define);
  38. };
  39. /**
  40. * Sets the mesh to use CPU skinning when needing to fallback.
  41. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  42. * @param mesh The mesh to use the fallbacks.
  43. */
  44. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  45. this._mesh = mesh;
  46. if (rank < this._currentRank) {
  47. this._currentRank = rank;
  48. }
  49. if (rank > this._maxRank) {
  50. this._maxRank = rank;
  51. }
  52. };
  53. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  54. /**
  55. * Checks to see if more fallbacks are still availible.
  56. */
  57. get: function () {
  58. return this._currentRank <= this._maxRank;
  59. },
  60. enumerable: true,
  61. configurable: true
  62. });
  63. /**
  64. * Removes the defines that shoould be removed when falling back.
  65. * @param currentDefines defines the current define statements for the shader.
  66. * @param effect defines the current effect we try to compile
  67. * @returns The resulting defines with defines of the current rank removed.
  68. */
  69. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  70. // First we try to switch to CPU skinning
  71. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  72. this._mesh.computeBonesUsingShaders = false;
  73. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  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 {
  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. this._uniformBuffersNames = {};
  163. this._isReady = false;
  164. this._compilationError = "";
  165. this.name = baseName;
  166. if (attributesNamesOrOptions.attributes) {
  167. var options = attributesNamesOrOptions;
  168. this._engine = uniformsNamesOrEngine;
  169. this._attributesNames = options.attributes;
  170. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  171. this._samplers = options.samplers.slice();
  172. this.defines = options.defines;
  173. this.onError = options.onError;
  174. this.onCompiled = options.onCompiled;
  175. this._fallbacks = options.fallbacks;
  176. this._indexParameters = options.indexParameters;
  177. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  178. if (options.uniformBuffersNames) {
  179. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  180. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  181. }
  182. }
  183. }
  184. else {
  185. this._engine = engine;
  186. this.defines = defines;
  187. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  188. this._samplers = samplers ? samplers.slice() : [];
  189. this._attributesNames = attributesNamesOrOptions;
  190. this.onError = onError;
  191. this.onCompiled = onCompiled;
  192. this._indexParameters = indexParameters;
  193. this._fallbacks = fallbacks;
  194. }
  195. this.uniqueId = Effect._uniqueIdSeed++;
  196. var vertexSource;
  197. var fragmentSource;
  198. if (baseName.vertexElement) {
  199. vertexSource = document.getElementById(baseName.vertexElement);
  200. if (!vertexSource) {
  201. vertexSource = baseName.vertexElement;
  202. }
  203. }
  204. else {
  205. vertexSource = baseName.vertex || baseName;
  206. }
  207. if (baseName.fragmentElement) {
  208. fragmentSource = document.getElementById(baseName.fragmentElement);
  209. if (!fragmentSource) {
  210. fragmentSource = baseName.fragmentElement;
  211. }
  212. }
  213. else {
  214. fragmentSource = baseName.fragment || baseName;
  215. }
  216. this._loadVertexShader(vertexSource, function (vertexCode) {
  217. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  218. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  219. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  220. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  221. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  222. if (baseName) {
  223. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  224. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  225. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  226. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  227. }
  228. else {
  229. _this._vertexSourceCode = migratedVertexCode;
  230. _this._fragmentSourceCode = migratedFragmentCode;
  231. }
  232. _this._prepareEffect();
  233. });
  234. });
  235. });
  236. });
  237. });
  238. });
  239. }
  240. Object.defineProperty(Effect.prototype, "key", {
  241. /**
  242. * Unique key for this effect
  243. */
  244. get: function () {
  245. return this._key;
  246. },
  247. enumerable: true,
  248. configurable: true
  249. });
  250. /**
  251. * If the effect has been compiled and prepared.
  252. * @returns if the effect is compiled and prepared.
  253. */
  254. Effect.prototype.isReady = function () {
  255. return this._isReady;
  256. };
  257. /**
  258. * The engine the effect was initialized with.
  259. * @returns the engine.
  260. */
  261. Effect.prototype.getEngine = function () {
  262. return this._engine;
  263. };
  264. /**
  265. * The compiled webGL program for the effect
  266. * @returns the webGL program.
  267. */
  268. Effect.prototype.getProgram = function () {
  269. return this._program;
  270. };
  271. /**
  272. * The set of names of attribute variables for the shader.
  273. * @returns An array of attribute names.
  274. */
  275. Effect.prototype.getAttributesNames = function () {
  276. return this._attributesNames;
  277. };
  278. /**
  279. * Returns the attribute at the given index.
  280. * @param index The index of the attribute.
  281. * @returns The location of the attribute.
  282. */
  283. Effect.prototype.getAttributeLocation = function (index) {
  284. return this._attributes[index];
  285. };
  286. /**
  287. * Returns the attribute based on the name of the variable.
  288. * @param name of the attribute to look up.
  289. * @returns the attribute location.
  290. */
  291. Effect.prototype.getAttributeLocationByName = function (name) {
  292. var index = this._attributesNames.indexOf(name);
  293. return this._attributes[index];
  294. };
  295. /**
  296. * The number of attributes.
  297. * @returns the numnber of attributes.
  298. */
  299. Effect.prototype.getAttributesCount = function () {
  300. return this._attributes.length;
  301. };
  302. /**
  303. * Gets the index of a uniform variable.
  304. * @param uniformName of the uniform to look up.
  305. * @returns the index.
  306. */
  307. Effect.prototype.getUniformIndex = function (uniformName) {
  308. return this._uniformsNames.indexOf(uniformName);
  309. };
  310. /**
  311. * Returns the attribute based on the name of the variable.
  312. * @param uniformName of the uniform to look up.
  313. * @returns the location of the uniform.
  314. */
  315. Effect.prototype.getUniform = function (uniformName) {
  316. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  317. };
  318. /**
  319. * Returns an array of sampler variable names
  320. * @returns The array of sampler variable neames.
  321. */
  322. Effect.prototype.getSamplers = function () {
  323. return this._samplers;
  324. };
  325. /**
  326. * The error from the last compilation.
  327. * @returns the error string.
  328. */
  329. Effect.prototype.getCompilationError = function () {
  330. return this._compilationError;
  331. };
  332. /**
  333. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  334. * @param func The callback to be used.
  335. */
  336. Effect.prototype.executeWhenCompiled = function (func) {
  337. if (this.isReady()) {
  338. func(this);
  339. return;
  340. }
  341. this.onCompileObservable.add(function (effect) {
  342. func(effect);
  343. });
  344. };
  345. /** @ignore */
  346. Effect.prototype._loadVertexShader = function (vertex, callback) {
  347. if (BABYLON.Tools.IsWindowObjectExist()) {
  348. // DOM element ?
  349. if (vertex instanceof HTMLElement) {
  350. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  351. callback(vertexCode);
  352. return;
  353. }
  354. }
  355. // Base64 encoded ?
  356. if (vertex.substr(0, 7) === "base64:") {
  357. var vertexBinary = window.atob(vertex.substr(7));
  358. callback(vertexBinary);
  359. return;
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  364. return;
  365. }
  366. var vertexShaderUrl;
  367. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  368. vertexShaderUrl = vertex;
  369. }
  370. else {
  371. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  372. }
  373. // Vertex shader
  374. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  375. };
  376. /** @ignore */
  377. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  378. if (BABYLON.Tools.IsWindowObjectExist()) {
  379. // DOM element ?
  380. if (fragment instanceof HTMLElement) {
  381. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  382. callback(fragmentCode);
  383. return;
  384. }
  385. }
  386. // Base64 encoded ?
  387. if (fragment.substr(0, 7) === "base64:") {
  388. var fragmentBinary = window.atob(fragment.substr(7));
  389. callback(fragmentBinary);
  390. return;
  391. }
  392. // Is in local store ?
  393. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  394. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  395. return;
  396. }
  397. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  398. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  399. return;
  400. }
  401. var fragmentShaderUrl;
  402. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  403. fragmentShaderUrl = fragment;
  404. }
  405. else {
  406. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  407. }
  408. // Fragment shader
  409. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  410. };
  411. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  412. // Rebuild shaders source code
  413. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  414. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  415. vertexCode = prefix + vertexCode;
  416. fragmentCode = prefix + fragmentCode;
  417. // Number lines of shaders source code
  418. var i = 2;
  419. var regex = /\n/gm;
  420. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  421. i = 2;
  422. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. // Dump shaders name and formatted source code
  424. if (this.name.vertexElement) {
  425. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  426. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  427. }
  428. else if (this.name.vertex) {
  429. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  430. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  431. }
  432. else {
  433. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  434. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  435. }
  436. };
  437. ;
  438. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  439. var preparedSourceCode = this._processPrecision(sourceCode);
  440. if (this._engine.webGLVersion == 1) {
  441. callback(preparedSourceCode);
  442. return;
  443. }
  444. // Already converted
  445. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  446. callback(preparedSourceCode.replace("#version 300 es", ""));
  447. return;
  448. }
  449. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  450. // Remove extensions
  451. // #extension GL_OES_standard_derivatives : enable
  452. // #extension GL_EXT_shader_texture_lod : enable
  453. // #extension GL_EXT_frag_depth : enable
  454. // #extension GL_EXT_draw_buffers : require
  455. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  456. var result = preparedSourceCode.replace(regex, "");
  457. // Migrate to GLSL v300
  458. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  459. result = result.replace(/attribute[ \t]/g, "in ");
  460. result = result.replace(/[ \t]attribute/g, " in");
  461. if (isFragment) {
  462. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  464. result = result.replace(/texture2D\s*\(/g, "texture(");
  465. result = result.replace(/textureCube\s*\(/g, "texture(");
  466. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  467. result = result.replace(/gl_FragColor/g, "glFragColor");
  468. result = result.replace(/gl_FragData/g, "glFragData");
  469. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  470. }
  471. callback(result);
  472. };
  473. Effect.prototype._processIncludes = function (sourceCode, callback) {
  474. var _this = this;
  475. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  476. var match = regex.exec(sourceCode);
  477. var returnValue = new String(sourceCode);
  478. while (match != null) {
  479. var includeFile = match[1];
  480. // Uniform declaration
  481. if (includeFile.indexOf("__decl__") !== -1) {
  482. includeFile = includeFile.replace(/__decl__/, "");
  483. if (this._engine.supportsUniformBuffers) {
  484. includeFile = includeFile.replace(/Vertex/, "Ubo");
  485. includeFile = includeFile.replace(/Fragment/, "Ubo");
  486. }
  487. includeFile = includeFile + "Declaration";
  488. }
  489. if (Effect.IncludesShadersStore[includeFile]) {
  490. // Substitution
  491. var includeContent = Effect.IncludesShadersStore[includeFile];
  492. if (match[2]) {
  493. var splits = match[3].split(",");
  494. for (var index = 0; index < splits.length; index += 2) {
  495. var source = new RegExp(splits[index], "g");
  496. var dest = splits[index + 1];
  497. includeContent = includeContent.replace(source, dest);
  498. }
  499. }
  500. if (match[4]) {
  501. var indexString = match[5];
  502. if (indexString.indexOf("..") !== -1) {
  503. var indexSplits = indexString.split("..");
  504. var minIndex = parseInt(indexSplits[0]);
  505. var maxIndex = parseInt(indexSplits[1]);
  506. var sourceIncludeContent = includeContent.slice(0);
  507. includeContent = "";
  508. if (isNaN(maxIndex)) {
  509. maxIndex = this._indexParameters[indexSplits[1]];
  510. }
  511. for (var i = minIndex; i < maxIndex; i++) {
  512. if (!this._engine.supportsUniformBuffers) {
  513. // Ubo replacement
  514. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  515. return p1 + "{X}";
  516. });
  517. }
  518. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  519. }
  520. }
  521. else {
  522. if (!this._engine.supportsUniformBuffers) {
  523. // Ubo replacement
  524. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  525. return p1 + "{X}";
  526. });
  527. }
  528. includeContent = includeContent.replace(/\{X\}/g, indexString);
  529. }
  530. }
  531. // Replace
  532. returnValue = returnValue.replace(match[0], includeContent);
  533. }
  534. else {
  535. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  536. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  537. Effect.IncludesShadersStore[includeFile] = fileContent;
  538. _this._processIncludes(returnValue, callback);
  539. });
  540. return;
  541. }
  542. match = regex.exec(sourceCode);
  543. }
  544. callback(returnValue);
  545. };
  546. Effect.prototype._processPrecision = function (source) {
  547. if (source.indexOf("precision highp float") === -1) {
  548. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  549. source = "precision mediump float;\n" + source;
  550. }
  551. else {
  552. source = "precision highp float;\n" + source;
  553. }
  554. }
  555. else {
  556. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  557. source = source.replace("precision highp float", "precision mediump float");
  558. }
  559. }
  560. return source;
  561. };
  562. /**
  563. * Recompiles the webGL program
  564. * @param vertexSourceCode The source code for the vertex shader.
  565. * @param fragmentSourceCode The source code for the fragment shader.
  566. * @param onCompiled Callback called when completed.
  567. * @param onError Callback called on error.
  568. */
  569. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  570. var _this = this;
  571. this._isReady = false;
  572. this._vertexSourceCodeOverride = vertexSourceCode;
  573. this._fragmentSourceCodeOverride = fragmentSourceCode;
  574. this.onError = function (effect, error) {
  575. if (onError) {
  576. onError(error);
  577. }
  578. };
  579. this.onCompiled = function () {
  580. var scenes = _this.getEngine().scenes;
  581. for (var i = 0; i < scenes.length; i++) {
  582. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  583. }
  584. if (onCompiled) {
  585. onCompiled(_this._program);
  586. }
  587. };
  588. this._fallbacks = null;
  589. this._prepareEffect();
  590. };
  591. /**
  592. * Gets the uniform locations of the the specified variable names
  593. * @param names THe names of the variables to lookup.
  594. * @returns Array of locations in the same order as variable names.
  595. */
  596. Effect.prototype.getSpecificUniformLocations = function (names) {
  597. var engine = this._engine;
  598. return engine.getUniforms(this._program, names);
  599. };
  600. /**
  601. * Prepares the effect
  602. */
  603. Effect.prototype._prepareEffect = function () {
  604. var attributesNames = this._attributesNames;
  605. var defines = this.defines;
  606. var fallbacks = this._fallbacks;
  607. this._valueCache = {};
  608. var previousProgram = this._program;
  609. try {
  610. var engine = this._engine;
  611. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  612. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  613. }
  614. else {
  615. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  616. }
  617. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  618. if (engine.supportsUniformBuffers) {
  619. for (var name in this._uniformBuffersNames) {
  620. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  621. }
  622. }
  623. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  624. this._attributes = engine.getAttributes(this._program, attributesNames);
  625. var index;
  626. for (index = 0; index < this._samplers.length; index++) {
  627. var sampler = this.getUniform(this._samplers[index]);
  628. if (sampler == null) {
  629. this._samplers.splice(index, 1);
  630. index--;
  631. }
  632. }
  633. engine.bindSamplers(this);
  634. this._compilationError = "";
  635. this._isReady = true;
  636. if (this.onCompiled) {
  637. this.onCompiled(this);
  638. }
  639. this.onCompileObservable.notifyObservers(this);
  640. this.onCompileObservable.clear();
  641. // Unbind mesh reference in fallbacks
  642. if (this._fallbacks) {
  643. this._fallbacks.unBindMesh();
  644. }
  645. if (previousProgram) {
  646. this.getEngine()._deleteProgram(previousProgram);
  647. }
  648. }
  649. catch (e) {
  650. this._compilationError = e.message;
  651. // Let's go through fallbacks then
  652. BABYLON.Tools.Error("Unable to compile effect:");
  653. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  654. return " " + uniform;
  655. }));
  656. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  657. return " " + attribute;
  658. }));
  659. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  660. BABYLON.Tools.Error("Error: " + this._compilationError);
  661. if (previousProgram) {
  662. this._program = previousProgram;
  663. this._isReady = true;
  664. if (this.onError) {
  665. this.onError(this, this._compilationError);
  666. }
  667. this.onErrorObservable.notifyObservers(this);
  668. }
  669. if (fallbacks && fallbacks.isMoreFallbacks) {
  670. BABYLON.Tools.Error("Trying next fallback.");
  671. this.defines = fallbacks.reduce(this.defines, this);
  672. this._prepareEffect();
  673. }
  674. else {
  675. if (this.onError) {
  676. this.onError(this, this._compilationError);
  677. }
  678. this.onErrorObservable.notifyObservers(this);
  679. this.onErrorObservable.clear();
  680. // Unbind mesh reference in fallbacks
  681. if (this._fallbacks) {
  682. this._fallbacks.unBindMesh();
  683. }
  684. }
  685. }
  686. };
  687. Object.defineProperty(Effect.prototype, "isSupported", {
  688. /**
  689. * Checks if the effect is supported. (Must be called after compilation)
  690. */
  691. get: function () {
  692. return this._compilationError === "";
  693. },
  694. enumerable: true,
  695. configurable: true
  696. });
  697. /**
  698. * Binds a texture to the engine to be used as output of the shader.
  699. * @param channel Name of the output variable.
  700. * @param texture Texture to bind.
  701. */
  702. Effect.prototype._bindTexture = function (channel, texture) {
  703. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  704. };
  705. /**
  706. * Sets a texture on the engine to be used in the shader.
  707. * @param channel Name of the sampler variable.
  708. * @param texture Texture to set.
  709. */
  710. Effect.prototype.setTexture = function (channel, texture) {
  711. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  712. };
  713. /**
  714. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  715. * @param channel Name of the sampler variable.
  716. * @param texture Texture to set.
  717. */
  718. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  719. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  720. };
  721. /**
  722. * Sets an array of textures on the engine to be used in the shader.
  723. * @param channel Name of the variable.
  724. * @param textures Textures to set.
  725. */
  726. Effect.prototype.setTextureArray = function (channel, textures) {
  727. if (this._samplers.indexOf(channel + "Ex") === -1) {
  728. var initialPos = this._samplers.indexOf(channel);
  729. for (var index = 1; index < textures.length; index++) {
  730. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  731. }
  732. }
  733. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  734. };
  735. /**
  736. * 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)
  737. * @param channel Name of the sampler variable.
  738. * @param postProcess Post process to get the input texture from.
  739. */
  740. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  741. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  742. };
  743. /**
  744. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  745. * 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)
  746. * @param channel Name of the sampler variable.
  747. * @param postProcess Post process to get the output texture from.
  748. */
  749. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  750. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  751. };
  752. /** @ignore */
  753. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  754. var cache = this._valueCache[uniformName];
  755. var flag = matrix.updateFlag;
  756. if (cache !== undefined && cache === flag) {
  757. return false;
  758. }
  759. this._valueCache[uniformName] = flag;
  760. return true;
  761. };
  762. /** @ignore */
  763. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  764. var cache = this._valueCache[uniformName];
  765. if (!cache) {
  766. cache = [x, y];
  767. this._valueCache[uniformName] = cache;
  768. return true;
  769. }
  770. var changed = false;
  771. if (cache[0] !== x) {
  772. cache[0] = x;
  773. changed = true;
  774. }
  775. if (cache[1] !== y) {
  776. cache[1] = y;
  777. changed = true;
  778. }
  779. return changed;
  780. };
  781. /** @ignore */
  782. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  783. var cache = this._valueCache[uniformName];
  784. if (!cache) {
  785. cache = [x, y, z];
  786. this._valueCache[uniformName] = cache;
  787. return true;
  788. }
  789. var changed = false;
  790. if (cache[0] !== x) {
  791. cache[0] = x;
  792. changed = true;
  793. }
  794. if (cache[1] !== y) {
  795. cache[1] = y;
  796. changed = true;
  797. }
  798. if (cache[2] !== z) {
  799. cache[2] = z;
  800. changed = true;
  801. }
  802. return changed;
  803. };
  804. /** @ignore */
  805. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  806. var cache = this._valueCache[uniformName];
  807. if (!cache) {
  808. cache = [x, y, z, w];
  809. this._valueCache[uniformName] = cache;
  810. return true;
  811. }
  812. var changed = false;
  813. if (cache[0] !== x) {
  814. cache[0] = x;
  815. changed = true;
  816. }
  817. if (cache[1] !== y) {
  818. cache[1] = y;
  819. changed = true;
  820. }
  821. if (cache[2] !== z) {
  822. cache[2] = z;
  823. changed = true;
  824. }
  825. if (cache[3] !== w) {
  826. cache[3] = w;
  827. changed = true;
  828. }
  829. return changed;
  830. };
  831. /**
  832. * Binds a buffer to a uniform.
  833. * @param buffer Buffer to bind.
  834. * @param name Name of the uniform variable to bind to.
  835. */
  836. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  837. var bufferName = this._uniformBuffersNames[name];
  838. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  839. return;
  840. }
  841. Effect._baseCache[bufferName] = buffer;
  842. this._engine.bindUniformBufferBase(buffer, bufferName);
  843. };
  844. /**
  845. * Binds block to a uniform.
  846. * @param blockName Name of the block to bind.
  847. * @param index Index to bind.
  848. */
  849. Effect.prototype.bindUniformBlock = function (blockName, index) {
  850. this._engine.bindUniformBlock(this._program, blockName, index);
  851. };
  852. /**
  853. * Sets an interger value on a uniform variable.
  854. * @param uniformName Name of the variable.
  855. * @param value Value to be set.
  856. * @returns this effect.
  857. */
  858. Effect.prototype.setInt = function (uniformName, value) {
  859. var cache = this._valueCache[uniformName];
  860. if (cache !== undefined && cache === value)
  861. return this;
  862. this._valueCache[uniformName] = value;
  863. this._engine.setInt(this.getUniform(uniformName), value);
  864. return this;
  865. };
  866. /**
  867. * Sets an int array on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param array array to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setIntArray = function (uniformName, array) {
  873. this._valueCache[uniformName] = null;
  874. this._engine.setIntArray(this.getUniform(uniformName), array);
  875. return this;
  876. };
  877. /**
  878. * 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)
  879. * @param uniformName Name of the variable.
  880. * @param array array to be set.
  881. * @returns this effect.
  882. */
  883. Effect.prototype.setIntArray2 = function (uniformName, array) {
  884. this._valueCache[uniformName] = null;
  885. this._engine.setIntArray2(this.getUniform(uniformName), array);
  886. return this;
  887. };
  888. /**
  889. * 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)
  890. * @param uniformName Name of the variable.
  891. * @param array array to be set.
  892. * @returns this effect.
  893. */
  894. Effect.prototype.setIntArray3 = function (uniformName, array) {
  895. this._valueCache[uniformName] = null;
  896. this._engine.setIntArray3(this.getUniform(uniformName), array);
  897. return this;
  898. };
  899. /**
  900. * 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)
  901. * @param uniformName Name of the variable.
  902. * @param array array to be set.
  903. * @returns this effect.
  904. */
  905. Effect.prototype.setIntArray4 = function (uniformName, array) {
  906. this._valueCache[uniformName] = null;
  907. this._engine.setIntArray4(this.getUniform(uniformName), array);
  908. return this;
  909. };
  910. /**
  911. * Sets an float array on a uniform variable.
  912. * @param uniformName Name of the variable.
  913. * @param array array to be set.
  914. * @returns this effect.
  915. */
  916. Effect.prototype.setFloatArray = function (uniformName, array) {
  917. this._valueCache[uniformName] = null;
  918. this._engine.setFloatArray(this.getUniform(uniformName), array);
  919. return this;
  920. };
  921. /**
  922. * 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)
  923. * @param uniformName Name of the variable.
  924. * @param array array to be set.
  925. * @returns this effect.
  926. */
  927. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  928. this._valueCache[uniformName] = null;
  929. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  930. return this;
  931. };
  932. /**
  933. * 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)
  934. * @param uniformName Name of the variable.
  935. * @param array array to be set.
  936. * @returns this effect.
  937. */
  938. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  939. this._valueCache[uniformName] = null;
  940. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  941. return this;
  942. };
  943. /**
  944. * 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)
  945. * @param uniformName Name of the variable.
  946. * @param array array to be set.
  947. * @returns this effect.
  948. */
  949. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  950. this._valueCache[uniformName] = null;
  951. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  952. return this;
  953. };
  954. /**
  955. * Sets an array on a uniform variable.
  956. * @param uniformName Name of the variable.
  957. * @param array array to be set.
  958. * @returns this effect.
  959. */
  960. Effect.prototype.setArray = function (uniformName, array) {
  961. this._valueCache[uniformName] = null;
  962. this._engine.setArray(this.getUniform(uniformName), array);
  963. return this;
  964. };
  965. /**
  966. * 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)
  967. * @param uniformName Name of the variable.
  968. * @param array array to be set.
  969. * @returns this effect.
  970. */
  971. Effect.prototype.setArray2 = function (uniformName, array) {
  972. this._valueCache[uniformName] = null;
  973. this._engine.setArray2(this.getUniform(uniformName), array);
  974. return this;
  975. };
  976. /**
  977. * 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)
  978. * @param uniformName Name of the variable.
  979. * @param array array to be set.
  980. * @returns this effect.
  981. */
  982. Effect.prototype.setArray3 = function (uniformName, array) {
  983. this._valueCache[uniformName] = null;
  984. this._engine.setArray3(this.getUniform(uniformName), array);
  985. return this;
  986. };
  987. /**
  988. * 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)
  989. * @param uniformName Name of the variable.
  990. * @param array array to be set.
  991. * @returns this effect.
  992. */
  993. Effect.prototype.setArray4 = function (uniformName, array) {
  994. this._valueCache[uniformName] = null;
  995. this._engine.setArray4(this.getUniform(uniformName), array);
  996. return this;
  997. };
  998. /**
  999. * Sets matrices on a uniform variable.
  1000. * @param uniformName Name of the variable.
  1001. * @param matrices matrices to be set.
  1002. * @returns this effect.
  1003. */
  1004. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1005. if (!matrices) {
  1006. return this;
  1007. }
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrix on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrix matrix to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1019. if (this._cacheMatrix(uniformName, matrix)) {
  1020. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1021. }
  1022. return this;
  1023. };
  1024. /**
  1025. * 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)
  1026. * @param uniformName Name of the variable.
  1027. * @param matrix matrix to be set.
  1028. * @returns this effect.
  1029. */
  1030. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1031. this._valueCache[uniformName] = null;
  1032. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1033. return this;
  1034. };
  1035. /**
  1036. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1037. * @param uniformName Name of the variable.
  1038. * @param matrix matrix to be set.
  1039. * @returns this effect.
  1040. */
  1041. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1042. this._valueCache[uniformName] = null;
  1043. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1044. return this;
  1045. };
  1046. /**
  1047. * Sets a float on a uniform variable.
  1048. * @param uniformName Name of the variable.
  1049. * @param value value to be set.
  1050. * @returns this effect.
  1051. */
  1052. Effect.prototype.setFloat = function (uniformName, value) {
  1053. var cache = this._valueCache[uniformName];
  1054. if (cache !== undefined && cache === value)
  1055. return this;
  1056. this._valueCache[uniformName] = value;
  1057. this._engine.setFloat(this.getUniform(uniformName), value);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a boolean on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param bool value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setBool = function (uniformName, bool) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === bool)
  1069. return this;
  1070. this._valueCache[uniformName] = bool;
  1071. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a Vector2 on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param vector2 vector2 to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1081. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1082. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1083. }
  1084. return this;
  1085. };
  1086. /**
  1087. * Sets a float2 on a uniform variable.
  1088. * @param uniformName Name of the variable.
  1089. * @param x First float in float2.
  1090. * @param y Second float in float2.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1094. if (this._cacheFloat2(uniformName, x, y)) {
  1095. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1096. }
  1097. return this;
  1098. };
  1099. /**
  1100. * Sets a Vector3 on a uniform variable.
  1101. * @param uniformName Name of the variable.
  1102. * @param vector3 Value to be set.
  1103. * @returns this effect.
  1104. */
  1105. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1106. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1107. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1108. }
  1109. return this;
  1110. };
  1111. /**
  1112. * Sets a float3 on a uniform variable.
  1113. * @param uniformName Name of the variable.
  1114. * @param x First float in float3.
  1115. * @param y Second float in float3.
  1116. * @param z Third float in float3.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1120. if (this._cacheFloat3(uniformName, x, y, z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a Vector4 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param vector4 Value to be set.
  1129. * @returns this effect.
  1130. */
  1131. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1132. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1133. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1134. }
  1135. return this;
  1136. };
  1137. /**
  1138. * Sets a float4 on a uniform variable.
  1139. * @param uniformName Name of the variable.
  1140. * @param x First float in float4.
  1141. * @param y Second float in float4.
  1142. * @param z Third float in float4.
  1143. * @param w Fourth float in float4.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1147. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1148. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a Color3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param color3 Value to be set.
  1156. * @returns this effect.
  1157. */
  1158. Effect.prototype.setColor3 = function (uniformName, color3) {
  1159. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1160. this._engine.setColor3(this.getUniform(uniformName), color3);
  1161. }
  1162. return this;
  1163. };
  1164. /**
  1165. * Sets a Color4 on a uniform variable.
  1166. * @param uniformName Name of the variable.
  1167. * @param color3 Value to be set.
  1168. * @param alpha Alpha value to be set.
  1169. * @returns this effect.
  1170. */
  1171. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1172. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1173. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1174. }
  1175. return this;
  1176. };
  1177. /**
  1178. * Sets a Color4 on a uniform variable
  1179. * @param uniformName defines the name of the variable
  1180. * @param color4 defines the value to be set
  1181. * @returns this effect.
  1182. */
  1183. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1184. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1185. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1186. }
  1187. return this;
  1188. };
  1189. /**
  1190. * Resets the cache of effects.
  1191. */
  1192. Effect.ResetCache = function () {
  1193. Effect._baseCache = {};
  1194. };
  1195. Effect._uniqueIdSeed = 0;
  1196. Effect._baseCache = {};
  1197. /**
  1198. * Store of each shader (The can be looked up using effect.key)
  1199. */
  1200. Effect.ShadersStore = {};
  1201. /**
  1202. * Store of each included file for a shader (The can be looked up using effect.key)
  1203. */
  1204. Effect.IncludesShadersStore = {};
  1205. return Effect;
  1206. }());
  1207. BABYLON.Effect = Effect;
  1208. })(BABYLON || (BABYLON = {}));
  1209. //# sourceMappingURL=babylon.effect.js.map
  1210. "use strict";
  1211. //# sourceMappingURL=babylon.types.js.map
  1212. "use strict";
  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. "use strict";
  1262. var BABYLON;
  1263. (function (BABYLON) {
  1264. var PointerEventTypes = /** @class */ (function () {
  1265. function PointerEventTypes() {
  1266. }
  1267. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1268. get: function () {
  1269. return PointerEventTypes._POINTERDOWN;
  1270. },
  1271. enumerable: true,
  1272. configurable: true
  1273. });
  1274. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1275. get: function () {
  1276. return PointerEventTypes._POINTERUP;
  1277. },
  1278. enumerable: true,
  1279. configurable: true
  1280. });
  1281. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1282. get: function () {
  1283. return PointerEventTypes._POINTERMOVE;
  1284. },
  1285. enumerable: true,
  1286. configurable: true
  1287. });
  1288. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1289. get: function () {
  1290. return PointerEventTypes._POINTERWHEEL;
  1291. },
  1292. enumerable: true,
  1293. configurable: true
  1294. });
  1295. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1296. get: function () {
  1297. return PointerEventTypes._POINTERPICK;
  1298. },
  1299. enumerable: true,
  1300. configurable: true
  1301. });
  1302. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1303. get: function () {
  1304. return PointerEventTypes._POINTERTAP;
  1305. },
  1306. enumerable: true,
  1307. configurable: true
  1308. });
  1309. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1310. get: function () {
  1311. return PointerEventTypes._POINTERDOUBLETAP;
  1312. },
  1313. enumerable: true,
  1314. configurable: true
  1315. });
  1316. PointerEventTypes._POINTERDOWN = 0x01;
  1317. PointerEventTypes._POINTERUP = 0x02;
  1318. PointerEventTypes._POINTERMOVE = 0x04;
  1319. PointerEventTypes._POINTERWHEEL = 0x08;
  1320. PointerEventTypes._POINTERPICK = 0x10;
  1321. PointerEventTypes._POINTERTAP = 0x20;
  1322. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1323. return PointerEventTypes;
  1324. }());
  1325. BABYLON.PointerEventTypes = PointerEventTypes;
  1326. var PointerInfoBase = /** @class */ (function () {
  1327. function PointerInfoBase(type, event) {
  1328. this.type = type;
  1329. this.event = event;
  1330. }
  1331. return PointerInfoBase;
  1332. }());
  1333. BABYLON.PointerInfoBase = PointerInfoBase;
  1334. /**
  1335. * This class is used to store pointer related info for the onPrePointerObservable event.
  1336. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1337. */
  1338. var PointerInfoPre = /** @class */ (function (_super) {
  1339. __extends(PointerInfoPre, _super);
  1340. function PointerInfoPre(type, event, localX, localY) {
  1341. var _this = _super.call(this, type, event) || this;
  1342. _this.skipOnPointerObservable = false;
  1343. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1344. return _this;
  1345. }
  1346. return PointerInfoPre;
  1347. }(PointerInfoBase));
  1348. BABYLON.PointerInfoPre = PointerInfoPre;
  1349. /**
  1350. * This type contains all the data related to a pointer event in Babylon.js.
  1351. * 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.
  1352. */
  1353. var PointerInfo = /** @class */ (function (_super) {
  1354. __extends(PointerInfo, _super);
  1355. function PointerInfo(type, event, pickInfo) {
  1356. var _this = _super.call(this, type, event) || this;
  1357. _this.pickInfo = pickInfo;
  1358. return _this;
  1359. }
  1360. return PointerInfo;
  1361. }(PointerInfoBase));
  1362. BABYLON.PointerInfo = PointerInfo;
  1363. })(BABYLON || (BABYLON = {}));
  1364. //# sourceMappingURL=babylon.pointerEvents.js.map
  1365. "use strict";
  1366. var BABYLON;
  1367. (function (BABYLON) {
  1368. BABYLON.ToGammaSpace = 1 / 2.2;
  1369. BABYLON.ToLinearSpace = 2.2;
  1370. BABYLON.Epsilon = 0.001;
  1371. /**
  1372. * Class used to hold a RBG color
  1373. */
  1374. var Color3 = /** @class */ (function () {
  1375. /**
  1376. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1377. * @param r defines the red component (between 0 and 1, default is 0)
  1378. * @param g defines the green component (between 0 and 1, default is 0)
  1379. * @param b defines the blue component (between 0 and 1, default is 0)
  1380. */
  1381. function Color3(
  1382. /**
  1383. * Defines the red component (between 0 and 1, default is 0)
  1384. */
  1385. r,
  1386. /**
  1387. * Defines the green component (between 0 and 1, default is 0)
  1388. */
  1389. g,
  1390. /**
  1391. * Defines the blue component (between 0 and 1, default is 0)
  1392. */
  1393. b) {
  1394. if (r === void 0) { r = 0; }
  1395. if (g === void 0) { g = 0; }
  1396. if (b === void 0) { b = 0; }
  1397. this.r = r;
  1398. this.g = g;
  1399. this.b = b;
  1400. }
  1401. /**
  1402. * Creates a string with the Color3 current values
  1403. * @returns the string representation of the Color3 object
  1404. */
  1405. Color3.prototype.toString = function () {
  1406. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1407. };
  1408. /**
  1409. * Returns the string "Color3"
  1410. * @returns "Color3"
  1411. */
  1412. Color3.prototype.getClassName = function () {
  1413. return "Color3";
  1414. };
  1415. /**
  1416. * Compute the Color3 hash code
  1417. * @returns an unique number that can be used to hash Color3 objects
  1418. */
  1419. Color3.prototype.getHashCode = function () {
  1420. var hash = this.r || 0;
  1421. hash = (hash * 397) ^ (this.g || 0);
  1422. hash = (hash * 397) ^ (this.b || 0);
  1423. return hash;
  1424. };
  1425. // Operators
  1426. /**
  1427. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1428. * @param array defines the array where to store the r,g,b components
  1429. * @param index defines an optional index in the target array to define where to start storing values
  1430. * @returns the current Color3 object
  1431. */
  1432. Color3.prototype.toArray = function (array, index) {
  1433. if (index === undefined) {
  1434. index = 0;
  1435. }
  1436. array[index] = this.r;
  1437. array[index + 1] = this.g;
  1438. array[index + 2] = this.b;
  1439. return this;
  1440. };
  1441. /**
  1442. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1443. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1444. * @returns a new {BABYLON.Color4} object
  1445. */
  1446. Color3.prototype.toColor4 = function (alpha) {
  1447. if (alpha === void 0) { alpha = 1; }
  1448. return new Color4(this.r, this.g, this.b, alpha);
  1449. };
  1450. /**
  1451. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1452. * @returns the new array
  1453. */
  1454. Color3.prototype.asArray = function () {
  1455. var result = new Array();
  1456. this.toArray(result, 0);
  1457. return result;
  1458. };
  1459. /**
  1460. * Returns the luminance value
  1461. * @returns a float value
  1462. */
  1463. Color3.prototype.toLuminance = function () {
  1464. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1465. };
  1466. /**
  1467. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1468. * @param otherColor defines the second operand
  1469. * @returns the new Color3 object
  1470. */
  1471. Color3.prototype.multiply = function (otherColor) {
  1472. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1473. };
  1474. /**
  1475. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1476. * @param otherColor defines the second operand
  1477. * @param result defines the Color3 object where to store the result
  1478. * @returns the current Color3
  1479. */
  1480. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1481. result.r = this.r * otherColor.r;
  1482. result.g = this.g * otherColor.g;
  1483. result.b = this.b * otherColor.b;
  1484. return this;
  1485. };
  1486. /**
  1487. * Determines equality between Color3 objects
  1488. * @param otherColor defines the second operand
  1489. * @returns true if the rgb values are equal to the passed ones
  1490. */
  1491. Color3.prototype.equals = function (otherColor) {
  1492. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1493. };
  1494. /**
  1495. * Determines equality between the current Color3 object and a set of r,b,g values
  1496. * @param r defines the red component to check
  1497. * @param g defines the green component to check
  1498. * @param b defines the blue component to check
  1499. * @returns true if the rgb values are equal to the passed ones
  1500. */
  1501. Color3.prototype.equalsFloats = function (r, g, b) {
  1502. return this.r === r && this.g === g && this.b === b;
  1503. };
  1504. /**
  1505. * Multiplies in place each rgb value by scale
  1506. * @param scale defines the scaling factor
  1507. * @returns the updated Color3
  1508. */
  1509. Color3.prototype.scale = function (scale) {
  1510. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1511. };
  1512. /**
  1513. * Multiplies the rgb values by scale and stores the result into "result"
  1514. * @param scale defines the scaling factor
  1515. * @param result defines the Color3 object where to store the result
  1516. * @returns the unmodified current Color3
  1517. */
  1518. Color3.prototype.scaleToRef = function (scale, result) {
  1519. result.r = this.r * scale;
  1520. result.g = this.g * scale;
  1521. result.b = this.b * scale;
  1522. return this;
  1523. };
  1524. /**
  1525. * Scale the current Color3 values by a factor and add the result to a given Color3
  1526. * @param scale defines the scale factor
  1527. * @param result defines color to store the result into
  1528. * @returns the unmodified current Color3
  1529. */
  1530. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1531. result.r += this.r * scale;
  1532. result.g += this.g * scale;
  1533. result.b += this.b * scale;
  1534. return this;
  1535. };
  1536. /**
  1537. * Clamps the rgb values by the min and max values and stores the result into "result"
  1538. * @param min defines minimum clamping value (default is 0)
  1539. * @param max defines maximum clamping value (default is 1)
  1540. * @param result defines color to store the result into
  1541. * @returns the original Color3
  1542. */
  1543. Color3.prototype.clampToRef = function (min, max, result) {
  1544. if (min === void 0) { min = 0; }
  1545. if (max === void 0) { max = 1; }
  1546. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1547. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1548. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1549. return this;
  1550. };
  1551. /**
  1552. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1553. * @param otherColor defines the second operand
  1554. * @returns the new Color3
  1555. */
  1556. Color3.prototype.add = function (otherColor) {
  1557. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1558. };
  1559. /**
  1560. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1561. * @param otherColor defines the second operand
  1562. * @param result defines Color3 object to store the result into
  1563. * @returns the unmodified current Color3
  1564. */
  1565. Color3.prototype.addToRef = function (otherColor, result) {
  1566. result.r = this.r + otherColor.r;
  1567. result.g = this.g + otherColor.g;
  1568. result.b = this.b + otherColor.b;
  1569. return this;
  1570. };
  1571. /**
  1572. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1573. * @param otherColor defines the second operand
  1574. * @returns the new Color3
  1575. */
  1576. Color3.prototype.subtract = function (otherColor) {
  1577. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1578. };
  1579. /**
  1580. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1581. * @param otherColor defines the second operand
  1582. * @param result defines Color3 object to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.subtractToRef = function (otherColor, result) {
  1586. result.r = this.r - otherColor.r;
  1587. result.g = this.g - otherColor.g;
  1588. result.b = this.b - otherColor.b;
  1589. return this;
  1590. };
  1591. /**
  1592. * Copy the current object
  1593. * @returns a new Color3 copied the current one
  1594. */
  1595. Color3.prototype.clone = function () {
  1596. return new Color3(this.r, this.g, this.b);
  1597. };
  1598. /**
  1599. * Copies the rgb values from the source in the current Color3
  1600. * @param source defines the source Color3 object
  1601. * @returns the updated Color3 object
  1602. */
  1603. Color3.prototype.copyFrom = function (source) {
  1604. this.r = source.r;
  1605. this.g = source.g;
  1606. this.b = source.b;
  1607. return this;
  1608. };
  1609. /**
  1610. * Updates the Color3 rgb values from the passed floats
  1611. * @param r defines the red component to read from
  1612. * @param g defines the green component to read from
  1613. * @param b defines the blue component to read from
  1614. * @returns the current Color3 object
  1615. */
  1616. Color3.prototype.copyFromFloats = function (r, g, b) {
  1617. this.r = r;
  1618. this.g = g;
  1619. this.b = b;
  1620. return this;
  1621. };
  1622. /**
  1623. * Updates the Color3 rgb values from the passed floats
  1624. * @param r defines the red component to read from
  1625. * @param g defines the green component to read from
  1626. * @param b defines the blue component to read from
  1627. * @returns the current Color3 object
  1628. */
  1629. Color3.prototype.set = function (r, g, b) {
  1630. return this.copyFromFloats(r, g, b);
  1631. };
  1632. /**
  1633. * Compute the Color3 hexadecimal code as a string
  1634. * @returns a string containing the hexadecimal representation of the Color3 object
  1635. */
  1636. Color3.prototype.toHexString = function () {
  1637. var intR = (this.r * 255) | 0;
  1638. var intG = (this.g * 255) | 0;
  1639. var intB = (this.b * 255) | 0;
  1640. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1641. };
  1642. /**
  1643. * Computes a new Color3 converted from the current one to linear space
  1644. * @returns a new Color3 object
  1645. */
  1646. Color3.prototype.toLinearSpace = function () {
  1647. var convertedColor = new Color3();
  1648. this.toLinearSpaceToRef(convertedColor);
  1649. return convertedColor;
  1650. };
  1651. /**
  1652. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1653. * @param convertedColor defines the Color3 object where to store the linear space version
  1654. * @returns the unmodified Color3
  1655. */
  1656. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1657. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1658. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1659. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1660. return this;
  1661. };
  1662. /**
  1663. * Computes a new Color3 converted from the current one to gamma space
  1664. * @returns a new Color3 object
  1665. */
  1666. Color3.prototype.toGammaSpace = function () {
  1667. var convertedColor = new Color3();
  1668. this.toGammaSpaceToRef(convertedColor);
  1669. return convertedColor;
  1670. };
  1671. /**
  1672. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1673. * @param convertedColor defines the Color3 object where to store the gamma space version
  1674. * @returns the unmodified Color3
  1675. */
  1676. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1677. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1678. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1679. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1680. return this;
  1681. };
  1682. // Statics
  1683. /**
  1684. * Creates a new Color3 from the string containing valid hexadecimal values
  1685. * @param hex defines a string containing valid hexadecimal values
  1686. * @returns a new Color3 object
  1687. */
  1688. Color3.FromHexString = function (hex) {
  1689. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1690. return new Color3(0, 0, 0);
  1691. }
  1692. var r = parseInt(hex.substring(1, 3), 16);
  1693. var g = parseInt(hex.substring(3, 5), 16);
  1694. var b = parseInt(hex.substring(5, 7), 16);
  1695. return Color3.FromInts(r, g, b);
  1696. };
  1697. /**
  1698. * Creates a new Vector3 from the starting index of the passed array
  1699. * @param array defines the source array
  1700. * @param offset defines an offset in the source array
  1701. * @returns a new Color3 object
  1702. */
  1703. Color3.FromArray = function (array, offset) {
  1704. if (offset === void 0) { offset = 0; }
  1705. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1706. };
  1707. /**
  1708. * Creates a new Color3 from integer values (< 256)
  1709. * @param r defines the red component to read from (value between 0 and 255)
  1710. * @param g defines the green component to read from (value between 0 and 255)
  1711. * @param b defines the blue component to read from (value between 0 and 255)
  1712. * @returns a new Color3 object
  1713. */
  1714. Color3.FromInts = function (r, g, b) {
  1715. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1716. };
  1717. /**
  1718. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1719. * @param start defines the start Color3 value
  1720. * @param end defines the end Color3 value
  1721. * @param amount defines the gradient value between start and end
  1722. * @returns a new Color3 object
  1723. */
  1724. Color3.Lerp = function (start, end, amount) {
  1725. var r = start.r + ((end.r - start.r) * amount);
  1726. var g = start.g + ((end.g - start.g) * amount);
  1727. var b = start.b + ((end.b - start.b) * amount);
  1728. return new Color3(r, g, b);
  1729. };
  1730. /**
  1731. * Returns a Color3 value containing a red color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Red = function () { return new Color3(1, 0, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a green color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Green = function () { return new Color3(0, 1, 0); };
  1740. /**
  1741. * Returns a Color3 value containing a blue color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1745. /**
  1746. * Returns a Color3 value containing a black color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.Black = function () { return new Color3(0, 0, 0); };
  1750. /**
  1751. * Returns a Color3 value containing a white color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.White = function () { return new Color3(1, 1, 1); };
  1755. /**
  1756. * Returns a Color3 value containing a purple color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1760. /**
  1761. * Returns a Color3 value containing a magenta color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1765. /**
  1766. * Returns a Color3 value containing a yellow color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1770. /**
  1771. * Returns a Color3 value containing a gray color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1775. /**
  1776. * Returns a Color3 value containing a teal color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1780. /**
  1781. * Returns a Color3 value containing a random color
  1782. * @returns a new Color3 object
  1783. */
  1784. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1785. return Color3;
  1786. }());
  1787. BABYLON.Color3 = Color3;
  1788. /**
  1789. * Class used to hold a RBGA color
  1790. */
  1791. var Color4 = /** @class */ (function () {
  1792. /**
  1793. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1794. * @param r defines the red component (between 0 and 1, default is 0)
  1795. * @param g defines the green component (between 0 and 1, default is 0)
  1796. * @param b defines the blue component (between 0 and 1, default is 0)
  1797. * @param a defines the alpha component (between 0 and 1, default is 1)
  1798. */
  1799. function Color4(
  1800. /**
  1801. * Defines the red component (between 0 and 1, default is 0)
  1802. */
  1803. r,
  1804. /**
  1805. * Defines the green component (between 0 and 1, default is 0)
  1806. */
  1807. g,
  1808. /**
  1809. * Defines the blue component (between 0 and 1, default is 0)
  1810. */
  1811. b,
  1812. /**
  1813. * Defines the alpha component (between 0 and 1, default is 1)
  1814. */
  1815. a) {
  1816. if (r === void 0) { r = 0; }
  1817. if (g === void 0) { g = 0; }
  1818. if (b === void 0) { b = 0; }
  1819. if (a === void 0) { a = 1; }
  1820. this.r = r;
  1821. this.g = g;
  1822. this.b = b;
  1823. this.a = a;
  1824. }
  1825. // Operators
  1826. /**
  1827. * Adds in place the passed Color4 values to the current Color4 object
  1828. * @param right defines the second operand
  1829. * @returns the current updated Color4 object
  1830. */
  1831. Color4.prototype.addInPlace = function (right) {
  1832. this.r += right.r;
  1833. this.g += right.g;
  1834. this.b += right.b;
  1835. this.a += right.a;
  1836. return this;
  1837. };
  1838. /**
  1839. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1840. * @returns the new array
  1841. */
  1842. Color4.prototype.asArray = function () {
  1843. var result = new Array();
  1844. this.toArray(result, 0);
  1845. return result;
  1846. };
  1847. /**
  1848. * Stores from the starting index in the passed array the Color4 successive values
  1849. * @param array defines the array where to store the r,g,b components
  1850. * @param index defines an optional index in the target array to define where to start storing values
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.toArray = function (array, index) {
  1854. if (index === undefined) {
  1855. index = 0;
  1856. }
  1857. array[index] = this.r;
  1858. array[index + 1] = this.g;
  1859. array[index + 2] = this.b;
  1860. array[index + 3] = this.a;
  1861. return this;
  1862. };
  1863. /**
  1864. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1865. * @param right defines the second operand
  1866. * @returns a new Color4 object
  1867. */
  1868. Color4.prototype.add = function (right) {
  1869. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1870. };
  1871. /**
  1872. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1873. * @param right defines the second operand
  1874. * @returns a new Color4 object
  1875. */
  1876. Color4.prototype.subtract = function (right) {
  1877. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1878. };
  1879. /**
  1880. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1881. * @param right defines the second operand
  1882. * @param result defines the Color4 object where to store the result
  1883. * @returns the current Color4 object
  1884. */
  1885. Color4.prototype.subtractToRef = function (right, result) {
  1886. result.r = this.r - right.r;
  1887. result.g = this.g - right.g;
  1888. result.b = this.b - right.b;
  1889. result.a = this.a - right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new Color4 with the current Color4 values multiplied by scale
  1894. * @param scale defines the scaling factor to apply
  1895. * @returns a new Color4 object
  1896. */
  1897. Color4.prototype.scale = function (scale) {
  1898. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1899. };
  1900. /**
  1901. * Multiplies the current Color4 values by scale and stores the result in "result"
  1902. * @param scale defines the scaling factor to apply
  1903. * @param result defines the Color4 object where to store the result
  1904. * @returns the current unmodified Color4
  1905. */
  1906. Color4.prototype.scaleToRef = function (scale, result) {
  1907. result.r = this.r * scale;
  1908. result.g = this.g * scale;
  1909. result.b = this.b * scale;
  1910. result.a = this.a * scale;
  1911. return this;
  1912. };
  1913. /**
  1914. * Scale the current Color4 values by a factor and add the result to a given Color4
  1915. * @param scale defines the scale factor
  1916. * @param result defines the Color4 object where to store the result
  1917. * @returns the unmodified current Color4
  1918. */
  1919. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1920. result.r += this.r * scale;
  1921. result.g += this.g * scale;
  1922. result.b += this.b * scale;
  1923. result.a += this.a * scale;
  1924. return this;
  1925. };
  1926. /**
  1927. * Clamps the rgb values by the min and max values and stores the result into "result"
  1928. * @param min defines minimum clamping value (default is 0)
  1929. * @param max defines maximum clamping value (default is 1)
  1930. * @param result defines color to store the result into.
  1931. * @returns the cuurent Color4
  1932. */
  1933. Color4.prototype.clampToRef = function (min, max, result) {
  1934. if (min === void 0) { min = 0; }
  1935. if (max === void 0) { max = 1; }
  1936. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1937. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1938. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1939. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1940. return this;
  1941. };
  1942. /**
  1943. * Multipy an Color4 value by another and return a new Color4 object
  1944. * @param color defines the Color4 value to multiply by
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.multiply = function (color) {
  1948. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1949. };
  1950. /**
  1951. * Multipy a Color4 value by another and push the result in a reference value
  1952. * @param color defines the Color4 value to multiply by
  1953. * @param result defines the Color4 to fill the result in
  1954. * @returns the result Color4
  1955. */
  1956. Color4.prototype.multiplyToRef = function (color, result) {
  1957. result.r = this.r * color.r;
  1958. result.g = this.g * color.g;
  1959. result.b = this.b * color.b;
  1960. result.a = this.a * color.a;
  1961. return result;
  1962. };
  1963. /**
  1964. * Creates a string with the Color4 current values
  1965. * @returns the string representation of the Color4 object
  1966. */
  1967. Color4.prototype.toString = function () {
  1968. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1969. };
  1970. /**
  1971. * Returns the string "Color4"
  1972. * @returns "Color4"
  1973. */
  1974. Color4.prototype.getClassName = function () {
  1975. return "Color4";
  1976. };
  1977. /**
  1978. * Compute the Color4 hash code
  1979. * @returns an unique number that can be used to hash Color4 objects
  1980. */
  1981. Color4.prototype.getHashCode = function () {
  1982. var hash = this.r || 0;
  1983. hash = (hash * 397) ^ (this.g || 0);
  1984. hash = (hash * 397) ^ (this.b || 0);
  1985. hash = (hash * 397) ^ (this.a || 0);
  1986. return hash;
  1987. };
  1988. /**
  1989. * Creates a new Color4 copied from the current one
  1990. * @returns a new Color4 object
  1991. */
  1992. Color4.prototype.clone = function () {
  1993. return new Color4(this.r, this.g, this.b, this.a);
  1994. };
  1995. /**
  1996. * Copies the passed Color4 values into the current one
  1997. * @param source defines the source Color4 object
  1998. * @returns the current updated Color4 object
  1999. */
  2000. Color4.prototype.copyFrom = function (source) {
  2001. this.r = source.r;
  2002. this.g = source.g;
  2003. this.b = source.b;
  2004. this.a = source.a;
  2005. return this;
  2006. };
  2007. /**
  2008. * Copies the passed float values into the current one
  2009. * @param r defines the red component to read from
  2010. * @param g defines the green component to read from
  2011. * @param b defines the blue component to read from
  2012. * @param a defines the alpha component to read from
  2013. * @returns the current updated Color4 object
  2014. */
  2015. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2016. this.r = r;
  2017. this.g = g;
  2018. this.b = b;
  2019. this.a = a;
  2020. return this;
  2021. };
  2022. /**
  2023. * Copies the passed float values into the current one
  2024. * @param r defines the red component to read from
  2025. * @param g defines the green component to read from
  2026. * @param b defines the blue component to read from
  2027. * @param a defines the alpha component to read from
  2028. * @returns the current updated Color4 object
  2029. */
  2030. Color4.prototype.set = function (r, g, b, a) {
  2031. return this.copyFromFloats(r, g, b, a);
  2032. };
  2033. /**
  2034. * Compute the Color4 hexadecimal code as a string
  2035. * @returns a string containing the hexadecimal representation of the Color4 object
  2036. */
  2037. Color4.prototype.toHexString = function () {
  2038. var intR = (this.r * 255) | 0;
  2039. var intG = (this.g * 255) | 0;
  2040. var intB = (this.b * 255) | 0;
  2041. var intA = (this.a * 255) | 0;
  2042. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2043. };
  2044. /**
  2045. * Computes a new Color4 converted from the current one to linear space
  2046. * @returns a new Color4 object
  2047. */
  2048. Color4.prototype.toLinearSpace = function () {
  2049. var convertedColor = new Color4();
  2050. this.toLinearSpaceToRef(convertedColor);
  2051. return convertedColor;
  2052. };
  2053. /**
  2054. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2055. * @param convertedColor defines the Color4 object where to store the linear space version
  2056. * @returns the unmodified Color4
  2057. */
  2058. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2059. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2060. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2061. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2062. convertedColor.a = this.a;
  2063. return this;
  2064. };
  2065. /**
  2066. * Computes a new Color4 converted from the current one to gamma space
  2067. * @returns a new Color4 object
  2068. */
  2069. Color4.prototype.toGammaSpace = function () {
  2070. var convertedColor = new Color4();
  2071. this.toGammaSpaceToRef(convertedColor);
  2072. return convertedColor;
  2073. };
  2074. /**
  2075. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2076. * @param convertedColor defines the Color4 object where to store the gamma space version
  2077. * @returns the unmodified Color4
  2078. */
  2079. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2080. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2081. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2082. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2083. convertedColor.a = this.a;
  2084. return this;
  2085. };
  2086. // Statics
  2087. /**
  2088. * Creates a new Color4 from the string containing valid hexadecimal values
  2089. * @param hex defines a string containing valid hexadecimal values
  2090. * @returns a new Color4 object
  2091. */
  2092. Color4.FromHexString = function (hex) {
  2093. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2094. return new Color4(0.0, 0.0, 0.0, 0.0);
  2095. }
  2096. var r = parseInt(hex.substring(1, 3), 16);
  2097. var g = parseInt(hex.substring(3, 5), 16);
  2098. var b = parseInt(hex.substring(5, 7), 16);
  2099. var a = parseInt(hex.substring(7, 9), 16);
  2100. return Color4.FromInts(r, g, b, a);
  2101. };
  2102. /**
  2103. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2104. * @param left defines the start value
  2105. * @param right defines the end value
  2106. * @param amount defines the gradient factor
  2107. * @returns a new Color4 object
  2108. */
  2109. Color4.Lerp = function (left, right, amount) {
  2110. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2111. Color4.LerpToRef(left, right, amount, result);
  2112. return result;
  2113. };
  2114. /**
  2115. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2116. * @param left defines the start value
  2117. * @param right defines the end value
  2118. * @param amount defines the gradient factor
  2119. * @param result defines the Color4 object where to store data
  2120. */
  2121. Color4.LerpToRef = function (left, right, amount, result) {
  2122. result.r = left.r + (right.r - left.r) * amount;
  2123. result.g = left.g + (right.g - left.g) * amount;
  2124. result.b = left.b + (right.b - left.b) * amount;
  2125. result.a = left.a + (right.a - left.a) * amount;
  2126. };
  2127. /**
  2128. * Creates a new Color4 from the starting index element of the passed array
  2129. * @param array defines the source array to read from
  2130. * @param offset defines the offset in the source array
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromArray = function (array, offset) {
  2134. if (offset === void 0) { offset = 0; }
  2135. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2136. };
  2137. /**
  2138. * Creates a new Color3 from integer values (< 256)
  2139. * @param r defines the red component to read from (value between 0 and 255)
  2140. * @param g defines the green component to read from (value between 0 and 255)
  2141. * @param b defines the blue component to read from (value between 0 and 255)
  2142. * @param a defines the alpha component to read from (value between 0 and 255)
  2143. * @returns a new Color3 object
  2144. */
  2145. Color4.FromInts = function (r, g, b, a) {
  2146. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2147. };
  2148. /**
  2149. * Check the content of a given array and convert it to an array containing RGBA data
  2150. * If the original array was already containing count * 4 values then it is returned directly
  2151. * @param colors defines the array to check
  2152. * @param count defines the number of RGBA data to expect
  2153. * @returns an array containing count * 4 values (RGBA)
  2154. */
  2155. Color4.CheckColors4 = function (colors, count) {
  2156. // Check if color3 was used
  2157. if (colors.length === count * 3) {
  2158. var colors4 = [];
  2159. for (var index = 0; index < colors.length; index += 3) {
  2160. var newIndex = (index / 3) * 4;
  2161. colors4[newIndex] = colors[index];
  2162. colors4[newIndex + 1] = colors[index + 1];
  2163. colors4[newIndex + 2] = colors[index + 2];
  2164. colors4[newIndex + 3] = 1.0;
  2165. }
  2166. return colors4;
  2167. }
  2168. return colors;
  2169. };
  2170. return Color4;
  2171. }());
  2172. BABYLON.Color4 = Color4;
  2173. var Vector2 = /** @class */ (function () {
  2174. /**
  2175. * Creates a new Vector2 from the passed x and y coordinates.
  2176. */
  2177. function Vector2(x, y) {
  2178. this.x = x;
  2179. this.y = y;
  2180. }
  2181. /**
  2182. * Returns a string with the Vector2 coordinates.
  2183. */
  2184. Vector2.prototype.toString = function () {
  2185. return "{X: " + this.x + " Y:" + this.y + "}";
  2186. };
  2187. /**
  2188. * Returns the string "Vector2"
  2189. */
  2190. Vector2.prototype.getClassName = function () {
  2191. return "Vector2";
  2192. };
  2193. /**
  2194. * Returns the Vector2 hash code as a number.
  2195. */
  2196. Vector2.prototype.getHashCode = function () {
  2197. var hash = this.x || 0;
  2198. hash = (hash * 397) ^ (this.y || 0);
  2199. return hash;
  2200. };
  2201. // Operators
  2202. /**
  2203. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2204. * Returns the Vector2.
  2205. */
  2206. Vector2.prototype.toArray = function (array, index) {
  2207. if (index === void 0) { index = 0; }
  2208. array[index] = this.x;
  2209. array[index + 1] = this.y;
  2210. return this;
  2211. };
  2212. /**
  2213. * Returns a new array with 2 elements : the Vector2 coordinates.
  2214. */
  2215. Vector2.prototype.asArray = function () {
  2216. var result = new Array();
  2217. this.toArray(result, 0);
  2218. return result;
  2219. };
  2220. /**
  2221. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2222. * Returns the updated Vector2.
  2223. */
  2224. Vector2.prototype.copyFrom = function (source) {
  2225. this.x = source.x;
  2226. this.y = source.y;
  2227. return this;
  2228. };
  2229. /**
  2230. * Sets the Vector2 coordinates with the passed floats.
  2231. * Returns the updated Vector2.
  2232. */
  2233. Vector2.prototype.copyFromFloats = function (x, y) {
  2234. this.x = x;
  2235. this.y = y;
  2236. return this;
  2237. };
  2238. /**
  2239. * Sets the Vector2 coordinates with the passed floats.
  2240. * Returns the updated Vector2.
  2241. */
  2242. Vector2.prototype.set = function (x, y) {
  2243. return this.copyFromFloats(x, y);
  2244. };
  2245. /**
  2246. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2247. */
  2248. Vector2.prototype.add = function (otherVector) {
  2249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2250. };
  2251. /**
  2252. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2253. * Returns the Vector2.
  2254. */
  2255. Vector2.prototype.addToRef = function (otherVector, result) {
  2256. result.x = this.x + otherVector.x;
  2257. result.y = this.y + otherVector.y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2262. * Returns the updated Vector2.
  2263. */
  2264. Vector2.prototype.addInPlace = function (otherVector) {
  2265. this.x += otherVector.x;
  2266. this.y += otherVector.y;
  2267. return this;
  2268. };
  2269. /**
  2270. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2271. */
  2272. Vector2.prototype.addVector3 = function (otherVector) {
  2273. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2274. };
  2275. /**
  2276. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2277. */
  2278. Vector2.prototype.subtract = function (otherVector) {
  2279. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2280. };
  2281. /**
  2282. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2283. * Returns the Vector2.
  2284. */
  2285. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2286. result.x = this.x - otherVector.x;
  2287. result.y = this.y - otherVector.y;
  2288. return this;
  2289. };
  2290. /**
  2291. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2292. * Returns the updated Vector2.
  2293. */
  2294. Vector2.prototype.subtractInPlace = function (otherVector) {
  2295. this.x -= otherVector.x;
  2296. this.y -= otherVector.y;
  2297. return this;
  2298. };
  2299. /**
  2300. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2301. * Returns the updated Vector2.
  2302. */
  2303. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2304. this.x *= otherVector.x;
  2305. this.y *= otherVector.y;
  2306. return this;
  2307. };
  2308. /**
  2309. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2310. */
  2311. Vector2.prototype.multiply = function (otherVector) {
  2312. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2313. };
  2314. /**
  2315. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2316. * Returns the Vector2.
  2317. */
  2318. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2319. result.x = this.x * otherVector.x;
  2320. result.y = this.y * otherVector.y;
  2321. return this;
  2322. };
  2323. /**
  2324. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2325. */
  2326. Vector2.prototype.multiplyByFloats = function (x, y) {
  2327. return new Vector2(this.x * x, this.y * y);
  2328. };
  2329. /**
  2330. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2331. */
  2332. Vector2.prototype.divide = function (otherVector) {
  2333. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2334. };
  2335. /**
  2336. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2337. * Returns the Vector2.
  2338. */
  2339. Vector2.prototype.divideToRef = function (otherVector, result) {
  2340. result.x = this.x / otherVector.x;
  2341. result.y = this.y / otherVector.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Divides the current Vector3 coordinates by the passed ones.
  2346. * Returns the updated Vector3.
  2347. */
  2348. Vector2.prototype.divideInPlace = function (otherVector) {
  2349. return this.divideToRef(otherVector, this);
  2350. };
  2351. /**
  2352. * Returns a new Vector2 with current Vector2 negated coordinates.
  2353. */
  2354. Vector2.prototype.negate = function () {
  2355. return new Vector2(-this.x, -this.y);
  2356. };
  2357. /**
  2358. * Multiply the Vector2 coordinates by scale.
  2359. * Returns the updated Vector2.
  2360. */
  2361. Vector2.prototype.scaleInPlace = function (scale) {
  2362. this.x *= scale;
  2363. this.y *= scale;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2368. */
  2369. Vector2.prototype.scale = function (scale) {
  2370. var result = new Vector2(0, 0);
  2371. this.scaleToRef(scale, result);
  2372. return result;
  2373. };
  2374. /**
  2375. * Scale the current Vector2 values by a factor to a given Vector2
  2376. * @param scale defines the scale factor
  2377. * @param result defines the Vector2 object where to store the result
  2378. * @returns the unmodified current Vector2
  2379. */
  2380. Vector2.prototype.scaleToRef = function (scale, result) {
  2381. result.x = this.x * scale;
  2382. result.y = this.y * scale;
  2383. return this;
  2384. };
  2385. /**
  2386. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2387. * @param scale defines the scale factor
  2388. * @param result defines the Vector2 object where to store the result
  2389. * @returns the unmodified current Vector2
  2390. */
  2391. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2392. result.x += this.x * scale;
  2393. result.y += this.y * scale;
  2394. return this;
  2395. };
  2396. /**
  2397. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2398. */
  2399. Vector2.prototype.equals = function (otherVector) {
  2400. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2401. };
  2402. /**
  2403. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2404. */
  2405. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2406. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2407. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2408. };
  2409. // Properties
  2410. /**
  2411. * Returns the vector length (float).
  2412. */
  2413. Vector2.prototype.length = function () {
  2414. return Math.sqrt(this.x * this.x + this.y * this.y);
  2415. };
  2416. /**
  2417. * Returns the vector squared length (float);
  2418. */
  2419. Vector2.prototype.lengthSquared = function () {
  2420. return (this.x * this.x + this.y * this.y);
  2421. };
  2422. // Methods
  2423. /**
  2424. * Normalize the vector.
  2425. * Returns the updated Vector2.
  2426. */
  2427. Vector2.prototype.normalize = function () {
  2428. var len = this.length();
  2429. if (len === 0)
  2430. return this;
  2431. var num = 1.0 / len;
  2432. this.x *= num;
  2433. this.y *= num;
  2434. return this;
  2435. };
  2436. /**
  2437. * Returns a new Vector2 copied from the Vector2.
  2438. */
  2439. Vector2.prototype.clone = function () {
  2440. return new Vector2(this.x, this.y);
  2441. };
  2442. // Statics
  2443. /**
  2444. * Returns a new Vector2(0, 0)
  2445. */
  2446. Vector2.Zero = function () {
  2447. return new Vector2(0, 0);
  2448. };
  2449. /**
  2450. * Returns a new Vector2(1, 1)
  2451. */
  2452. Vector2.One = function () {
  2453. return new Vector2(1, 1);
  2454. };
  2455. /**
  2456. * Returns a new Vector2 set from the passed index element of the passed array.
  2457. */
  2458. Vector2.FromArray = function (array, offset) {
  2459. if (offset === void 0) { offset = 0; }
  2460. return new Vector2(array[offset], array[offset + 1]);
  2461. };
  2462. /**
  2463. * Sets "result" from the passed index element of the passed array.
  2464. */
  2465. Vector2.FromArrayToRef = function (array, offset, result) {
  2466. result.x = array[offset];
  2467. result.y = array[offset + 1];
  2468. };
  2469. /**
  2470. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2471. */
  2472. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2473. var squared = amount * amount;
  2474. var cubed = amount * squared;
  2475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2481. return new Vector2(x, y);
  2482. };
  2483. /**
  2484. * 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".
  2485. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2486. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2487. */
  2488. Vector2.Clamp = function (value, min, max) {
  2489. var x = value.x;
  2490. x = (x > max.x) ? max.x : x;
  2491. x = (x < min.x) ? min.x : x;
  2492. var y = value.y;
  2493. y = (y > max.y) ? max.y : y;
  2494. y = (y < min.y) ? min.y : y;
  2495. return new Vector2(x, y);
  2496. };
  2497. /**
  2498. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2499. */
  2500. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2501. var squared = amount * amount;
  2502. var cubed = amount * squared;
  2503. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2504. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2505. var part3 = (cubed - (2.0 * squared)) + amount;
  2506. var part4 = cubed - squared;
  2507. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2508. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2509. return new Vector2(x, y);
  2510. };
  2511. /**
  2512. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2513. */
  2514. Vector2.Lerp = function (start, end, amount) {
  2515. var x = start.x + ((end.x - start.x) * amount);
  2516. var y = start.y + ((end.y - start.y) * amount);
  2517. return new Vector2(x, y);
  2518. };
  2519. /**
  2520. * Returns the dot product (float) of the vector "left" and the vector "right".
  2521. */
  2522. Vector2.Dot = function (left, right) {
  2523. return left.x * right.x + left.y * right.y;
  2524. };
  2525. /**
  2526. * Returns a new Vector2 equal to the normalized passed vector.
  2527. */
  2528. Vector2.Normalize = function (vector) {
  2529. var newVector = vector.clone();
  2530. newVector.normalize();
  2531. return newVector;
  2532. };
  2533. /**
  2534. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2535. */
  2536. Vector2.Minimize = function (left, right) {
  2537. var x = (left.x < right.x) ? left.x : right.x;
  2538. var y = (left.y < right.y) ? left.y : right.y;
  2539. return new Vector2(x, y);
  2540. };
  2541. /**
  2542. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2543. */
  2544. Vector2.Maximize = function (left, right) {
  2545. var x = (left.x > right.x) ? left.x : right.x;
  2546. var y = (left.y > right.y) ? left.y : right.y;
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2551. */
  2552. Vector2.Transform = function (vector, transformation) {
  2553. var r = Vector2.Zero();
  2554. Vector2.TransformToRef(vector, transformation, r);
  2555. return r;
  2556. };
  2557. /**
  2558. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2559. */
  2560. Vector2.TransformToRef = function (vector, transformation, result) {
  2561. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2562. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2563. result.x = x;
  2564. result.y = y;
  2565. };
  2566. /**
  2567. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2568. */
  2569. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2570. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2571. var sign = a < 0 ? -1 : 1;
  2572. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2573. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2574. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2575. };
  2576. /**
  2577. * Returns the distance (float) between the vectors "value1" and "value2".
  2578. */
  2579. Vector2.Distance = function (value1, value2) {
  2580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2581. };
  2582. /**
  2583. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2584. */
  2585. Vector2.DistanceSquared = function (value1, value2) {
  2586. var x = value1.x - value2.x;
  2587. var y = value1.y - value2.y;
  2588. return (x * x) + (y * y);
  2589. };
  2590. /**
  2591. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2592. */
  2593. Vector2.Center = function (value1, value2) {
  2594. var center = value1.add(value2);
  2595. center.scaleInPlace(0.5);
  2596. return center;
  2597. };
  2598. /**
  2599. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2600. */
  2601. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2602. var l2 = Vector2.DistanceSquared(segA, segB);
  2603. if (l2 === 0.0) {
  2604. return Vector2.Distance(p, segA);
  2605. }
  2606. var v = segB.subtract(segA);
  2607. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2608. var proj = segA.add(v.multiplyByFloats(t, t));
  2609. return Vector2.Distance(p, proj);
  2610. };
  2611. return Vector2;
  2612. }());
  2613. BABYLON.Vector2 = Vector2;
  2614. /**
  2615. * Classed used to store (x,y,z) vector representation
  2616. * A Vector3 is the main object used in 3D geometry
  2617. * It can represent etiher the coordinates of a point the space, either a direction
  2618. * Reminder: Babylon.js uses a left handed forward facing system
  2619. */
  2620. var Vector3 = /** @class */ (function () {
  2621. /**
  2622. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2623. * @param x defines the first coordinates (on X axis)
  2624. * @param y defines the second coordinates (on Y axis)
  2625. * @param z defines the third coordinates (on Z axis)
  2626. */
  2627. function Vector3(
  2628. /**
  2629. * Defines the first coordinates (on X axis)
  2630. */
  2631. x,
  2632. /**
  2633. * Defines the second coordinates (on Y axis)
  2634. */
  2635. y,
  2636. /**
  2637. * Defines the third coordinates (on Z axis)
  2638. */
  2639. z) {
  2640. this.x = x;
  2641. this.y = y;
  2642. this.z = z;
  2643. }
  2644. /**
  2645. * Creates a string representation of the Vector3
  2646. * @returns a string with the Vector3 coordinates.
  2647. */
  2648. Vector3.prototype.toString = function () {
  2649. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2650. };
  2651. /**
  2652. * Gets the class name
  2653. * @returns the string "Vector3"
  2654. */
  2655. Vector3.prototype.getClassName = function () {
  2656. return "Vector3";
  2657. };
  2658. /**
  2659. * Creates the Vector3 hash code
  2660. * @returns a number which tends to be unique between Vector3 instances
  2661. */
  2662. Vector3.prototype.getHashCode = function () {
  2663. var hash = this.x || 0;
  2664. hash = (hash * 397) ^ (this.y || 0);
  2665. hash = (hash * 397) ^ (this.z || 0);
  2666. return hash;
  2667. };
  2668. // Operators
  2669. /**
  2670. * Creates an array containing three elements : the coordinates of the Vector3
  2671. * @returns a new array of numbers
  2672. */
  2673. Vector3.prototype.asArray = function () {
  2674. var result = [];
  2675. this.toArray(result, 0);
  2676. return result;
  2677. };
  2678. /**
  2679. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2680. * @param array defines the destination array
  2681. * @param index defines the offset in the destination array
  2682. * @returns the current Vector3
  2683. */
  2684. Vector3.prototype.toArray = function (array, index) {
  2685. if (index === void 0) { index = 0; }
  2686. array[index] = this.x;
  2687. array[index + 1] = this.y;
  2688. array[index + 2] = this.z;
  2689. return this;
  2690. };
  2691. /**
  2692. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2693. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2694. */
  2695. Vector3.prototype.toQuaternion = function () {
  2696. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2697. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2698. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2699. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2700. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2701. var cosy = Math.cos(this.y * 0.5);
  2702. var siny = Math.sin(this.y * 0.5);
  2703. result.x = coszMinusx * siny;
  2704. result.y = -sinzMinusx * siny;
  2705. result.z = sinxPlusz * cosy;
  2706. result.w = cosxPlusz * cosy;
  2707. return result;
  2708. };
  2709. /**
  2710. * Adds the passed vector to the current Vector3
  2711. * @param otherVector defines the second operand
  2712. * @returns the current updated Vector3
  2713. */
  2714. Vector3.prototype.addInPlace = function (otherVector) {
  2715. this.x += otherVector.x;
  2716. this.y += otherVector.y;
  2717. this.z += otherVector.z;
  2718. return this;
  2719. };
  2720. /**
  2721. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2722. * @param otherVector defines the second operand
  2723. * @returns the resulting Vector3
  2724. */
  2725. Vector3.prototype.add = function (otherVector) {
  2726. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2727. };
  2728. /**
  2729. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2730. * @param otherVector defines the second operand
  2731. * @param result defines the Vector3 object where to store the result
  2732. * @returns the current Vector3
  2733. */
  2734. Vector3.prototype.addToRef = function (otherVector, result) {
  2735. result.x = this.x + otherVector.x;
  2736. result.y = this.y + otherVector.y;
  2737. result.z = this.z + otherVector.z;
  2738. return this;
  2739. };
  2740. /**
  2741. * Subtract the passed vector from the current Vector3
  2742. * @param otherVector defines the second operand
  2743. * @returns the current updated Vector3
  2744. */
  2745. Vector3.prototype.subtractInPlace = function (otherVector) {
  2746. this.x -= otherVector.x;
  2747. this.y -= otherVector.y;
  2748. this.z -= otherVector.z;
  2749. return this;
  2750. };
  2751. /**
  2752. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2753. * @param otherVector defines the second operand
  2754. * @returns the resulting Vector3
  2755. */
  2756. Vector3.prototype.subtract = function (otherVector) {
  2757. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2758. };
  2759. /**
  2760. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2761. * @param otherVector defines the second operand
  2762. * @param result defines the Vector3 object where to store the result
  2763. * @returns the current Vector3
  2764. */
  2765. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2766. result.x = this.x - otherVector.x;
  2767. result.y = this.y - otherVector.y;
  2768. result.z = this.z - otherVector.z;
  2769. return this;
  2770. };
  2771. /**
  2772. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2773. * @param x defines the x coordinate of the operand
  2774. * @param y defines the y coordinate of the operand
  2775. * @param z defines the z coordinate of the operand
  2776. * @returns the resulting Vector3
  2777. */
  2778. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2779. return new Vector3(this.x - x, this.y - y, this.z - z);
  2780. };
  2781. /**
  2782. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @param result defines the Vector3 object where to store the result
  2787. * @returns the current Vector3
  2788. */
  2789. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2790. result.x = this.x - x;
  2791. result.y = this.y - y;
  2792. result.z = this.z - z;
  2793. return this;
  2794. };
  2795. /**
  2796. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2797. * @returns a new Vector3
  2798. */
  2799. Vector3.prototype.negate = function () {
  2800. return new Vector3(-this.x, -this.y, -this.z);
  2801. };
  2802. /**
  2803. * Multiplies the Vector3 coordinates by the float "scale"
  2804. * @param scale defines the multiplier factor
  2805. * @returns the current updated Vector3
  2806. */
  2807. Vector3.prototype.scaleInPlace = function (scale) {
  2808. this.x *= scale;
  2809. this.y *= scale;
  2810. this.z *= scale;
  2811. return this;
  2812. };
  2813. /**
  2814. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2815. * @param scale defines the multiplier factor
  2816. * @returns a new Vector3
  2817. */
  2818. Vector3.prototype.scale = function (scale) {
  2819. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2820. };
  2821. /**
  2822. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2823. * @param scale defines the multiplier factor
  2824. * @param result defines the Vector3 object where to store the result
  2825. * @returns the current Vector3
  2826. */
  2827. Vector3.prototype.scaleToRef = function (scale, result) {
  2828. result.x = this.x * scale;
  2829. result.y = this.y * scale;
  2830. result.z = this.z * scale;
  2831. return this;
  2832. };
  2833. /**
  2834. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2835. * @param scale defines the scale factor
  2836. * @param result defines the Vector3 object where to store the result
  2837. * @returns the unmodified current Vector3
  2838. */
  2839. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2840. result.x += this.x * scale;
  2841. result.y += this.y * scale;
  2842. result.z += this.z * scale;
  2843. return this;
  2844. };
  2845. /**
  2846. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2847. * @param otherVector defines the second operand
  2848. * @returns true if both vectors are equals
  2849. */
  2850. Vector3.prototype.equals = function (otherVector) {
  2851. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2852. };
  2853. /**
  2854. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2855. * @param otherVector defines the second operand
  2856. * @param epsilon defines the minimal distance to define values as equals
  2857. * @returns true if both vectors are distant less than epsilon
  2858. */
  2859. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2860. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2861. 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);
  2862. };
  2863. /**
  2864. * Returns true if the current Vector3 coordinates equals the passed floats
  2865. * @param x defines the x coordinate of the operand
  2866. * @param y defines the y coordinate of the operand
  2867. * @param z defines the z coordinate of the operand
  2868. * @returns true if both vectors are equals
  2869. */
  2870. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2871. return this.x === x && this.y === y && this.z === z;
  2872. };
  2873. /**
  2874. * Multiplies the current Vector3 coordinates by the passed ones
  2875. * @param otherVector defines the second operand
  2876. * @returns the current updated Vector3
  2877. */
  2878. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2879. this.x *= otherVector.x;
  2880. this.y *= otherVector.y;
  2881. this.z *= otherVector.z;
  2882. return this;
  2883. };
  2884. /**
  2885. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2886. * @param otherVector defines the second operand
  2887. * @returns the new Vector3
  2888. */
  2889. Vector3.prototype.multiply = function (otherVector) {
  2890. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2891. };
  2892. /**
  2893. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2894. * @param otherVector defines the second operand
  2895. * @param result defines the Vector3 object where to store the result
  2896. * @returns the current Vector3
  2897. */
  2898. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2899. result.x = this.x * otherVector.x;
  2900. result.y = this.y * otherVector.y;
  2901. result.z = this.z * otherVector.z;
  2902. return this;
  2903. };
  2904. /**
  2905. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2906. * @param x defines the x coordinate of the operand
  2907. * @param y defines the y coordinate of the operand
  2908. * @param z defines the z coordinate of the operand
  2909. * @returns the new Vector3
  2910. */
  2911. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2912. return new Vector3(this.x * x, this.y * y, this.z * z);
  2913. };
  2914. /**
  2915. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2916. * @param otherVector defines the second operand
  2917. * @returns the new Vector3
  2918. */
  2919. Vector3.prototype.divide = function (otherVector) {
  2920. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2921. };
  2922. /**
  2923. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2924. * @param otherVector defines the second operand
  2925. * @param result defines the Vector3 object where to store the result
  2926. * @returns the current Vector3
  2927. */
  2928. Vector3.prototype.divideToRef = function (otherVector, result) {
  2929. result.x = this.x / otherVector.x;
  2930. result.y = this.y / otherVector.y;
  2931. result.z = this.z / otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Divides the current Vector3 coordinates by the passed ones.
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.divideInPlace = function (otherVector) {
  2940. return this.divideToRef(otherVector, this);
  2941. };
  2942. /**
  2943. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2944. * @param other defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.minimizeInPlace = function (other) {
  2948. if (other.x < this.x)
  2949. this.x = other.x;
  2950. if (other.y < this.y)
  2951. this.y = other.y;
  2952. if (other.z < this.z)
  2953. this.z = other.z;
  2954. return this;
  2955. };
  2956. /**
  2957. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2958. * @param other defines the second operand
  2959. * @returns the current updated Vector3
  2960. */
  2961. Vector3.prototype.maximizeInPlace = function (other) {
  2962. if (other.x > this.x)
  2963. this.x = other.x;
  2964. if (other.y > this.y)
  2965. this.y = other.y;
  2966. if (other.z > this.z)
  2967. this.z = other.z;
  2968. return this;
  2969. };
  2970. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2971. /**
  2972. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2973. */
  2974. get: function () {
  2975. var absX = Math.abs(this.x);
  2976. var absY = Math.abs(this.y);
  2977. if (absX !== absY) {
  2978. return true;
  2979. }
  2980. var absZ = Math.abs(this.z);
  2981. if (absX !== absZ) {
  2982. return true;
  2983. }
  2984. if (absY !== absZ) {
  2985. return true;
  2986. }
  2987. return false;
  2988. },
  2989. enumerable: true,
  2990. configurable: true
  2991. });
  2992. // Properties
  2993. /**
  2994. * Gets the length of the Vector3
  2995. * @returns the length of the Vecto3
  2996. */
  2997. Vector3.prototype.length = function () {
  2998. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2999. };
  3000. /**
  3001. * Gets the squared length of the Vector3
  3002. * @returns squared length of the Vector3
  3003. */
  3004. Vector3.prototype.lengthSquared = function () {
  3005. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3006. };
  3007. /**
  3008. * Normalize the current Vector3.
  3009. * Please note that this is an in place operation.
  3010. * @returns the current updated Vector3
  3011. */
  3012. Vector3.prototype.normalize = function () {
  3013. var len = this.length();
  3014. if (len === 0 || len === 1.0)
  3015. return this;
  3016. var num = 1.0 / len;
  3017. this.x *= num;
  3018. this.y *= num;
  3019. this.z *= num;
  3020. return this;
  3021. };
  3022. /**
  3023. * Normalize the current Vector3 to a new vector
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.normalizeToNew = function () {
  3027. var normalized = new Vector3(0, 0, 0);
  3028. this.normalizeToRef(normalized);
  3029. return normalized;
  3030. };
  3031. /**
  3032. * Normalize the current Vector3 to the reference
  3033. * @param reference define the Vector3 to update
  3034. * @returns the updated Vector3
  3035. */
  3036. Vector3.prototype.normalizeToRef = function (reference) {
  3037. var len = this.length();
  3038. if (len === 0 || len === 1.0) {
  3039. reference.set(this.x, this.y, this.z);
  3040. return reference;
  3041. }
  3042. var scale = 1.0 / len;
  3043. this.scaleToRef(scale, reference);
  3044. return reference;
  3045. };
  3046. /**
  3047. * Creates a new Vector3 copied from the current Vector3
  3048. * @returns the new Vector3
  3049. */
  3050. Vector3.prototype.clone = function () {
  3051. return new Vector3(this.x, this.y, this.z);
  3052. };
  3053. /**
  3054. * Copies the passed vector coordinates to the current Vector3 ones
  3055. * @param source defines the source Vector3
  3056. * @returns the current updated Vector3
  3057. */
  3058. Vector3.prototype.copyFrom = function (source) {
  3059. this.x = source.x;
  3060. this.y = source.y;
  3061. this.z = source.z;
  3062. return this;
  3063. };
  3064. /**
  3065. * Copies the passed floats to the current Vector3 coordinates
  3066. * @param x defines the x coordinate of the operand
  3067. * @param y defines the y coordinate of the operand
  3068. * @param z defines the z coordinate of the operand
  3069. * @returns the current updated Vector3
  3070. */
  3071. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3072. this.x = x;
  3073. this.y = y;
  3074. this.z = z;
  3075. return this;
  3076. };
  3077. /**
  3078. * Copies the passed floats to the current Vector3 coordinates
  3079. * @param x defines the x coordinate of the operand
  3080. * @param y defines the y coordinate of the operand
  3081. * @param z defines the z coordinate of the operand
  3082. * @returns the current updated Vector3
  3083. */
  3084. Vector3.prototype.set = function (x, y, z) {
  3085. return this.copyFromFloats(x, y, z);
  3086. };
  3087. // Statics
  3088. /**
  3089. * Get the clip factor between two vectors
  3090. * @param vector0 defines the first operand
  3091. * @param vector1 defines the second operand
  3092. * @param axis defines the axis to use
  3093. * @param size defines the size along the axis
  3094. * @returns the clip factor
  3095. */
  3096. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3097. var d0 = Vector3.Dot(vector0, axis) - size;
  3098. var d1 = Vector3.Dot(vector1, axis) - size;
  3099. var s = d0 / (d0 - d1);
  3100. return s;
  3101. };
  3102. /**
  3103. * Get angle between two vectors
  3104. * @param vector0 angle between vector0 and vector1
  3105. * @param vector1 angle between vector0 and vector1
  3106. * @param normal direction of the normal
  3107. * @return the angle between vector0 and vector1
  3108. */
  3109. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3110. var v0 = vector0.clone().normalize();
  3111. var v1 = vector1.clone().normalize();
  3112. var dot = Vector3.Dot(v0, v1);
  3113. var n = Vector3.Cross(v0, v1);
  3114. if (Vector3.Dot(n, normal) > 0) {
  3115. return Math.acos(dot);
  3116. }
  3117. return -Math.acos(dot);
  3118. };
  3119. /**
  3120. * Returns a new Vector3 set from the index "offset" of the passed array
  3121. * @param array defines the source array
  3122. * @param offset defines the offset in the source array
  3123. * @returns the new Vector3
  3124. */
  3125. Vector3.FromArray = function (array, offset) {
  3126. if (!offset) {
  3127. offset = 0;
  3128. }
  3129. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3130. };
  3131. /**
  3132. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3133. * This function is deprecated. Use FromArray instead
  3134. * @param array defines the source array
  3135. * @param offset defines the offset in the source array
  3136. * @returns the new Vector3
  3137. */
  3138. Vector3.FromFloatArray = function (array, offset) {
  3139. return Vector3.FromArray(array, offset);
  3140. };
  3141. /**
  3142. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3143. * @param array defines the source array
  3144. * @param offset defines the offset in the source array
  3145. * @param result defines the Vector3 where to store the result
  3146. */
  3147. Vector3.FromArrayToRef = function (array, offset, result) {
  3148. result.x = array[offset];
  3149. result.y = array[offset + 1];
  3150. result.z = array[offset + 2];
  3151. };
  3152. /**
  3153. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3154. * This function is deprecated. Use FromArrayToRef instead.
  3155. * @param array defines the source array
  3156. * @param offset defines the offset in the source array
  3157. * @param result defines the Vector3 where to store the result
  3158. */
  3159. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3160. return Vector3.FromArrayToRef(array, offset, result);
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" with the passed floats.
  3164. * @param x defines the x coordinate of the source
  3165. * @param y defines the y coordinate of the source
  3166. * @param z defines the z coordinate of the source
  3167. * @param result defines the Vector3 where to store the result
  3168. */
  3169. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3170. result.x = x;
  3171. result.y = y;
  3172. result.z = z;
  3173. };
  3174. /**
  3175. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3176. * @returns a new empty Vector3
  3177. */
  3178. Vector3.Zero = function () {
  3179. return new Vector3(0.0, 0.0, 0.0);
  3180. };
  3181. /**
  3182. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3183. * @returns a new unit Vector3
  3184. */
  3185. Vector3.One = function () {
  3186. return new Vector3(1.0, 1.0, 1.0);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3190. * @returns a new up Vector3
  3191. */
  3192. Vector3.Up = function () {
  3193. return new Vector3(0.0, 1.0, 0.0);
  3194. };
  3195. /**
  3196. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3197. * @returns a new forward Vector3
  3198. */
  3199. Vector3.Forward = function () {
  3200. return new Vector3(0.0, 0.0, 1.0);
  3201. };
  3202. /**
  3203. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3204. * @returns a new right Vector3
  3205. */
  3206. Vector3.Right = function () {
  3207. return new Vector3(1.0, 0.0, 0.0);
  3208. };
  3209. /**
  3210. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3211. * @returns a new left Vector3
  3212. */
  3213. Vector3.Left = function () {
  3214. return new Vector3(-1.0, 0.0, 0.0);
  3215. };
  3216. /**
  3217. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3218. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3219. * @param vector defines the Vector3 to transform
  3220. * @param transformation defines the transformation matrix
  3221. * @returns the transformed Vector3
  3222. */
  3223. Vector3.TransformCoordinates = function (vector, transformation) {
  3224. var result = Vector3.Zero();
  3225. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3226. return result;
  3227. };
  3228. /**
  3229. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3230. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3231. * @param vector defines the Vector3 to transform
  3232. * @param transformation defines the transformation matrix
  3233. * @param result defines the Vector3 where to store the result
  3234. */
  3235. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3236. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3237. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3238. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3239. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3240. result.x = x / w;
  3241. result.y = y / w;
  3242. result.z = z / w;
  3243. };
  3244. /**
  3245. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3246. * This method computes tranformed coordinates only, not transformed direction vectors
  3247. * @param x define the x coordinate of the source vector
  3248. * @param y define the y coordinate of the source vector
  3249. * @param z define the z coordinate of the source vector
  3250. * @param transformation defines the transformation matrix
  3251. * @param result defines the Vector3 where to store the result
  3252. */
  3253. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3254. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3255. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3256. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3257. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3258. result.x = rx / rw;
  3259. result.y = ry / rw;
  3260. result.z = rz / rw;
  3261. };
  3262. /**
  3263. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3264. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3265. * @param vector defines the Vector3 to transform
  3266. * @param transformation defines the transformation matrix
  3267. * @returns the new Vector3
  3268. */
  3269. Vector3.TransformNormal = function (vector, transformation) {
  3270. var result = Vector3.Zero();
  3271. Vector3.TransformNormalToRef(vector, transformation, result);
  3272. return result;
  3273. };
  3274. /**
  3275. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3276. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3277. * @param vector defines the Vector3 to transform
  3278. * @param transformation defines the transformation matrix
  3279. * @param result defines the Vector3 where to store the result
  3280. */
  3281. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3282. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3283. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3284. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3285. result.x = x;
  3286. result.y = y;
  3287. result.z = z;
  3288. };
  3289. /**
  3290. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3291. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3292. * @param x define the x coordinate of the source vector
  3293. * @param y define the y coordinate of the source vector
  3294. * @param z define the z coordinate of the source vector
  3295. * @param transformation defines the transformation matrix
  3296. * @param result defines the Vector3 where to store the result
  3297. */
  3298. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3299. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3300. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3301. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3302. };
  3303. /**
  3304. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3305. * @param value1 defines the first control point
  3306. * @param value2 defines the second control point
  3307. * @param value3 defines the third control point
  3308. * @param value4 defines the fourth control point
  3309. * @param amount defines the amount on the spline to use
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3313. var squared = amount * amount;
  3314. var cubed = amount * squared;
  3315. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3316. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3317. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3318. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3319. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3320. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3321. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3322. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3323. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3324. return new Vector3(x, y, z);
  3325. };
  3326. /**
  3327. * 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"
  3328. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3329. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3330. * @param value defines the current value
  3331. * @param min defines the lower range value
  3332. * @param max defines the upper range value
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.Clamp = function (value, min, max) {
  3336. var x = value.x;
  3337. x = (x > max.x) ? max.x : x;
  3338. x = (x < min.x) ? min.x : x;
  3339. var y = value.y;
  3340. y = (y > max.y) ? max.y : y;
  3341. y = (y < min.y) ? min.y : y;
  3342. var z = value.z;
  3343. z = (z > max.z) ? max.z : z;
  3344. z = (z < min.z) ? min.z : z;
  3345. return new Vector3(x, y, z);
  3346. };
  3347. /**
  3348. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3349. * @param value1 defines the first control point
  3350. * @param tangent1 defines the first tangent vector
  3351. * @param value2 defines the second control point
  3352. * @param tangent2 defines the second tangent vector
  3353. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3354. * @returns the new Vector3
  3355. */
  3356. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3357. var squared = amount * amount;
  3358. var cubed = amount * squared;
  3359. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3360. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3361. var part3 = (cubed - (2.0 * squared)) + amount;
  3362. var part4 = cubed - squared;
  3363. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3364. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3365. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3366. return new Vector3(x, y, z);
  3367. };
  3368. /**
  3369. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3370. * @param start defines the start value
  3371. * @param end defines the end value
  3372. * @param amount max defines amount between both (between 0 and 1)
  3373. * @returns the new Vector3
  3374. */
  3375. Vector3.Lerp = function (start, end, amount) {
  3376. var result = new Vector3(0, 0, 0);
  3377. Vector3.LerpToRef(start, end, amount, result);
  3378. return result;
  3379. };
  3380. /**
  3381. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3382. * @param start defines the start value
  3383. * @param end defines the end value
  3384. * @param amount max defines amount between both (between 0 and 1)
  3385. * @param result defines the Vector3 where to store the result
  3386. */
  3387. Vector3.LerpToRef = function (start, end, amount, result) {
  3388. result.x = start.x + ((end.x - start.x) * amount);
  3389. result.y = start.y + ((end.y - start.y) * amount);
  3390. result.z = start.z + ((end.z - start.z) * amount);
  3391. };
  3392. /**
  3393. * Returns the dot product (float) between the vectors "left" and "right"
  3394. * @param left defines the left operand
  3395. * @param right defines the right operand
  3396. * @returns the dot product
  3397. */
  3398. Vector3.Dot = function (left, right) {
  3399. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3400. };
  3401. /**
  3402. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3403. * The cross product is then orthogonal to both "left" and "right"
  3404. * @param left defines the left operand
  3405. * @param right defines the right operand
  3406. * @returns the cross product
  3407. */
  3408. Vector3.Cross = function (left, right) {
  3409. var result = Vector3.Zero();
  3410. Vector3.CrossToRef(left, right, result);
  3411. return result;
  3412. };
  3413. /**
  3414. * Sets the passed vector "result" with the cross product of "left" and "right"
  3415. * The cross product is then orthogonal to both "left" and "right"
  3416. * @param left defines the left operand
  3417. * @param right defines the right operand
  3418. * @param result defines the Vector3 where to store the result
  3419. */
  3420. Vector3.CrossToRef = function (left, right, result) {
  3421. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3422. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3423. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3424. result.copyFrom(MathTmp.Vector3[0]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 as the normalization of the passed vector
  3428. * @param vector defines the Vector3 to normalize
  3429. * @returns the new Vector3
  3430. */
  3431. Vector3.Normalize = function (vector) {
  3432. var result = Vector3.Zero();
  3433. Vector3.NormalizeToRef(vector, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * Sets the passed vector "result" with the normalization of the passed first vector
  3438. * @param vector defines the Vector3 to normalize
  3439. * @param result defines the Vector3 where to store the result
  3440. */
  3441. Vector3.NormalizeToRef = function (vector, result) {
  3442. result.copyFrom(vector);
  3443. result.normalize();
  3444. };
  3445. /**
  3446. * Project a Vector3 onto screen space
  3447. * @param vector defines the Vector3 to project
  3448. * @param world defines the world matrix to use
  3449. * @param transform defines the transform (view x projection) matrix to use
  3450. * @param viewport defines the screen viewport to use
  3451. * @returns the new Vector3
  3452. */
  3453. Vector3.Project = function (vector, world, transform, viewport) {
  3454. var cw = viewport.width;
  3455. var ch = viewport.height;
  3456. var cx = viewport.x;
  3457. var cy = viewport.y;
  3458. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3459. 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);
  3460. var matrix = MathTmp.Matrix[0];
  3461. world.multiplyToRef(transform, matrix);
  3462. matrix.multiplyToRef(viewportMatrix, matrix);
  3463. return Vector3.TransformCoordinates(vector, matrix);
  3464. };
  3465. /**
  3466. * Unproject from screen space to object space
  3467. * @param source defines the screen space Vector3 to use
  3468. * @param viewportWidth defines the current width of the viewport
  3469. * @param viewportHeight defines the current height of the viewport
  3470. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3471. * @param transform defines the transform (view x projection) matrix to use
  3472. * @returns the new Vector3
  3473. */
  3474. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3475. var matrix = MathTmp.Matrix[0];
  3476. world.multiplyToRef(transform, matrix);
  3477. matrix.invert();
  3478. source.x = source.x / viewportWidth * 2 - 1;
  3479. source.y = -(source.y / viewportHeight * 2 - 1);
  3480. var vector = Vector3.TransformCoordinates(source, matrix);
  3481. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3482. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3483. vector = vector.scale(1.0 / num);
  3484. }
  3485. return vector;
  3486. };
  3487. /**
  3488. * Unproject from screen space to object space
  3489. * @param source defines the screen space Vector3 to use
  3490. * @param viewportWidth defines the current width of the viewport
  3491. * @param viewportHeight defines the current height of the viewport
  3492. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3493. * @param view defines the view matrix to use
  3494. * @param projection defines the projection matrix to use
  3495. * @returns the new Vector3
  3496. */
  3497. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3498. var result = Vector3.Zero();
  3499. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Unproject from screen space to object space
  3504. * @param source defines the screen space Vector3 to use
  3505. * @param viewportWidth defines the current width of the viewport
  3506. * @param viewportHeight defines the current height of the viewport
  3507. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3508. * @param view defines the view matrix to use
  3509. * @param projection defines the projection matrix to use
  3510. * @param result defines the Vector3 where to store the result
  3511. */
  3512. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3513. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3514. };
  3515. /**
  3516. * Unproject from screen space to object space
  3517. * @param sourceX defines the screen space x coordinate to use
  3518. * @param sourceY defines the screen space y coordinate to use
  3519. * @param sourceZ defines the screen space z coordinate to use
  3520. * @param viewportWidth defines the current width of the viewport
  3521. * @param viewportHeight defines the current height of the viewport
  3522. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3523. * @param view defines the view matrix to use
  3524. * @param projection defines the projection matrix to use
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3528. var matrix = MathTmp.Matrix[0];
  3529. world.multiplyToRef(view, matrix);
  3530. matrix.multiplyToRef(projection, matrix);
  3531. matrix.invert();
  3532. var screenSource = MathTmp.Vector3[0];
  3533. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3534. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3535. screenSource.z = 2 * sourceZ - 1.0;
  3536. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3537. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3538. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3539. result.scaleInPlace(1.0 / num);
  3540. }
  3541. };
  3542. /**
  3543. * Gets the minimal coordinate values between two Vector3
  3544. * @param left defines the first operand
  3545. * @param right defines the second operand
  3546. * @returns the new Vector3
  3547. */
  3548. Vector3.Minimize = function (left, right) {
  3549. var min = left.clone();
  3550. min.minimizeInPlace(right);
  3551. return min;
  3552. };
  3553. /**
  3554. * Gets the maximal coordinate values between two Vector3
  3555. * @param left defines the first operand
  3556. * @param right defines the second operand
  3557. * @returns the new Vector3
  3558. */
  3559. Vector3.Maximize = function (left, right) {
  3560. var max = left.clone();
  3561. max.maximizeInPlace(right);
  3562. return max;
  3563. };
  3564. /**
  3565. * Returns the distance between the vectors "value1" and "value2"
  3566. * @param value1 defines the first operand
  3567. * @param value2 defines the second operand
  3568. * @returns the distance
  3569. */
  3570. Vector3.Distance = function (value1, value2) {
  3571. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3572. };
  3573. /**
  3574. * Returns the squared distance between the vectors "value1" and "value2"
  3575. * @param value1 defines the first operand
  3576. * @param value2 defines the second operand
  3577. * @returns the squared distance
  3578. */
  3579. Vector3.DistanceSquared = function (value1, value2) {
  3580. var x = value1.x - value2.x;
  3581. var y = value1.y - value2.y;
  3582. var z = value1.z - value2.z;
  3583. return (x * x) + (y * y) + (z * z);
  3584. };
  3585. /**
  3586. * Returns a new Vector3 located at the center between "value1" and "value2"
  3587. * @param value1 defines the first operand
  3588. * @param value2 defines the second operand
  3589. * @returns the new Vector3
  3590. */
  3591. Vector3.Center = function (value1, value2) {
  3592. var center = value1.add(value2);
  3593. center.scaleInPlace(0.5);
  3594. return center;
  3595. };
  3596. /**
  3597. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3598. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3599. * to something in order to rotate it from its local system to the given target system
  3600. * Note: axis1, axis2 and axis3 are normalized during this operation
  3601. * @param axis1 defines the first axis
  3602. * @param axis2 defines the second axis
  3603. * @param axis3 defines the third axis
  3604. * @returns a new Vector3
  3605. */
  3606. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3607. var rotation = Vector3.Zero();
  3608. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3609. return rotation;
  3610. };
  3611. /**
  3612. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3613. * @param axis1 defines the first axis
  3614. * @param axis2 defines the second axis
  3615. * @param axis3 defines the third axis
  3616. * @param ref defines the Vector3 where to store the result
  3617. */
  3618. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3619. var quat = MathTmp.Quaternion[0];
  3620. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3621. quat.toEulerAnglesToRef(ref);
  3622. };
  3623. return Vector3;
  3624. }());
  3625. BABYLON.Vector3 = Vector3;
  3626. //Vector4 class created for EulerAngle class conversion to Quaternion
  3627. var Vector4 = /** @class */ (function () {
  3628. /**
  3629. * Creates a Vector4 object from the passed floats.
  3630. */
  3631. function Vector4(x, y, z, w) {
  3632. this.x = x;
  3633. this.y = y;
  3634. this.z = z;
  3635. this.w = w;
  3636. }
  3637. /**
  3638. * Returns the string with the Vector4 coordinates.
  3639. */
  3640. Vector4.prototype.toString = function () {
  3641. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3642. };
  3643. /**
  3644. * Returns the string "Vector4".
  3645. */
  3646. Vector4.prototype.getClassName = function () {
  3647. return "Vector4";
  3648. };
  3649. /**
  3650. * Returns the Vector4 hash code.
  3651. */
  3652. Vector4.prototype.getHashCode = function () {
  3653. var hash = this.x || 0;
  3654. hash = (hash * 397) ^ (this.y || 0);
  3655. hash = (hash * 397) ^ (this.z || 0);
  3656. hash = (hash * 397) ^ (this.w || 0);
  3657. return hash;
  3658. };
  3659. // Operators
  3660. /**
  3661. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3662. */
  3663. Vector4.prototype.asArray = function () {
  3664. var result = new Array();
  3665. this.toArray(result, 0);
  3666. return result;
  3667. };
  3668. /**
  3669. * Populates the passed array from the passed index with the Vector4 coordinates.
  3670. * Returns the Vector4.
  3671. */
  3672. Vector4.prototype.toArray = function (array, index) {
  3673. if (index === undefined) {
  3674. index = 0;
  3675. }
  3676. array[index] = this.x;
  3677. array[index + 1] = this.y;
  3678. array[index + 2] = this.z;
  3679. array[index + 3] = this.w;
  3680. return this;
  3681. };
  3682. /**
  3683. * Adds the passed vector to the current Vector4.
  3684. * Returns the updated Vector4.
  3685. */
  3686. Vector4.prototype.addInPlace = function (otherVector) {
  3687. this.x += otherVector.x;
  3688. this.y += otherVector.y;
  3689. this.z += otherVector.z;
  3690. this.w += otherVector.w;
  3691. return this;
  3692. };
  3693. /**
  3694. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3695. */
  3696. Vector4.prototype.add = function (otherVector) {
  3697. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3698. };
  3699. /**
  3700. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3701. * Returns the current Vector4.
  3702. */
  3703. Vector4.prototype.addToRef = function (otherVector, result) {
  3704. result.x = this.x + otherVector.x;
  3705. result.y = this.y + otherVector.y;
  3706. result.z = this.z + otherVector.z;
  3707. result.w = this.w + otherVector.w;
  3708. return this;
  3709. };
  3710. /**
  3711. * Subtract in place the passed vector from the current Vector4.
  3712. * Returns the updated Vector4.
  3713. */
  3714. Vector4.prototype.subtractInPlace = function (otherVector) {
  3715. this.x -= otherVector.x;
  3716. this.y -= otherVector.y;
  3717. this.z -= otherVector.z;
  3718. this.w -= otherVector.w;
  3719. return this;
  3720. };
  3721. /**
  3722. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3723. */
  3724. Vector4.prototype.subtract = function (otherVector) {
  3725. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3726. };
  3727. /**
  3728. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3729. * Returns the current Vector4.
  3730. */
  3731. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3732. result.x = this.x - otherVector.x;
  3733. result.y = this.y - otherVector.y;
  3734. result.z = this.z - otherVector.z;
  3735. result.w = this.w - otherVector.w;
  3736. return this;
  3737. };
  3738. /**
  3739. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3740. */
  3741. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3742. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3743. };
  3744. /**
  3745. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. * Returns the current Vector4.
  3747. */
  3748. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3749. result.x = this.x - x;
  3750. result.y = this.y - y;
  3751. result.z = this.z - z;
  3752. result.w = this.w - w;
  3753. return this;
  3754. };
  3755. /**
  3756. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3757. */
  3758. Vector4.prototype.negate = function () {
  3759. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3760. };
  3761. /**
  3762. * Multiplies the current Vector4 coordinates by scale (float).
  3763. * Returns the updated Vector4.
  3764. */
  3765. Vector4.prototype.scaleInPlace = function (scale) {
  3766. this.x *= scale;
  3767. this.y *= scale;
  3768. this.z *= scale;
  3769. this.w *= scale;
  3770. return this;
  3771. };
  3772. /**
  3773. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3774. */
  3775. Vector4.prototype.scale = function (scale) {
  3776. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3777. };
  3778. /**
  3779. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3780. * Returns the current Vector4.
  3781. */
  3782. Vector4.prototype.scaleToRef = function (scale, result) {
  3783. result.x = this.x * scale;
  3784. result.y = this.y * scale;
  3785. result.z = this.z * scale;
  3786. result.w = this.w * scale;
  3787. return this;
  3788. };
  3789. /**
  3790. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3791. * @param scale defines the scale factor
  3792. * @param result defines the Vector4 object where to store the result
  3793. * @returns the unmodified current Vector4
  3794. */
  3795. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3796. result.x += this.x * scale;
  3797. result.y += this.y * scale;
  3798. result.z += this.z * scale;
  3799. result.w += this.w * scale;
  3800. return this;
  3801. };
  3802. /**
  3803. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3804. */
  3805. Vector4.prototype.equals = function (otherVector) {
  3806. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3807. };
  3808. /**
  3809. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3810. */
  3811. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3812. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3813. return otherVector
  3814. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3815. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3816. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3817. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3818. };
  3819. /**
  3820. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3821. */
  3822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3823. return this.x === x && this.y === y && this.z === z && this.w === w;
  3824. };
  3825. /**
  3826. * Multiplies in place the current Vector4 by the passed one.
  3827. * Returns the updated Vector4.
  3828. */
  3829. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3830. this.x *= otherVector.x;
  3831. this.y *= otherVector.y;
  3832. this.z *= otherVector.z;
  3833. this.w *= otherVector.w;
  3834. return this;
  3835. };
  3836. /**
  3837. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3838. */
  3839. Vector4.prototype.multiply = function (otherVector) {
  3840. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3841. };
  3842. /**
  3843. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3844. * Returns the current Vector4.
  3845. */
  3846. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3847. result.x = this.x * otherVector.x;
  3848. result.y = this.y * otherVector.y;
  3849. result.z = this.z * otherVector.z;
  3850. result.w = this.w * otherVector.w;
  3851. return this;
  3852. };
  3853. /**
  3854. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3855. */
  3856. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3857. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3861. */
  3862. Vector4.prototype.divide = function (otherVector) {
  3863. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3864. };
  3865. /**
  3866. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3867. * Returns the current Vector4.
  3868. */
  3869. Vector4.prototype.divideToRef = function (otherVector, result) {
  3870. result.x = this.x / otherVector.x;
  3871. result.y = this.y / otherVector.y;
  3872. result.z = this.z / otherVector.z;
  3873. result.w = this.w / otherVector.w;
  3874. return this;
  3875. };
  3876. /**
  3877. * Divides the current Vector3 coordinates by the passed ones.
  3878. * @returns the updated Vector3.
  3879. */
  3880. Vector4.prototype.divideInPlace = function (otherVector) {
  3881. return this.divideToRef(otherVector, this);
  3882. };
  3883. /**
  3884. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3885. * @param other defines the second operand
  3886. * @returns the current updated Vector4
  3887. */
  3888. Vector4.prototype.minimizeInPlace = function (other) {
  3889. if (other.x < this.x)
  3890. this.x = other.x;
  3891. if (other.y < this.y)
  3892. this.y = other.y;
  3893. if (other.z < this.z)
  3894. this.z = other.z;
  3895. if (other.w < this.w)
  3896. this.w = other.w;
  3897. return this;
  3898. };
  3899. /**
  3900. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3901. * @param other defines the second operand
  3902. * @returns the current updated Vector4
  3903. */
  3904. Vector4.prototype.maximizeInPlace = function (other) {
  3905. if (other.x > this.x)
  3906. this.x = other.x;
  3907. if (other.y > this.y)
  3908. this.y = other.y;
  3909. if (other.z > this.z)
  3910. this.z = other.z;
  3911. if (other.w > this.w)
  3912. this.w = other.w;
  3913. return this;
  3914. };
  3915. // Properties
  3916. /**
  3917. * Returns the Vector4 length (float).
  3918. */
  3919. Vector4.prototype.length = function () {
  3920. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3921. };
  3922. /**
  3923. * Returns the Vector4 squared length (float).
  3924. */
  3925. Vector4.prototype.lengthSquared = function () {
  3926. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3927. };
  3928. // Methods
  3929. /**
  3930. * Normalizes in place the Vector4.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.normalize = function () {
  3934. var len = this.length();
  3935. if (len === 0)
  3936. return this;
  3937. var num = 1.0 / len;
  3938. this.x *= num;
  3939. this.y *= num;
  3940. this.z *= num;
  3941. this.w *= num;
  3942. return this;
  3943. };
  3944. /**
  3945. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3946. */
  3947. Vector4.prototype.toVector3 = function () {
  3948. return new Vector3(this.x, this.y, this.z);
  3949. };
  3950. /**
  3951. * Returns a new Vector4 copied from the current one.
  3952. */
  3953. Vector4.prototype.clone = function () {
  3954. return new Vector4(this.x, this.y, this.z, this.w);
  3955. };
  3956. /**
  3957. * Updates the current Vector4 with the passed one coordinates.
  3958. * Returns the updated Vector4.
  3959. */
  3960. Vector4.prototype.copyFrom = function (source) {
  3961. this.x = source.x;
  3962. this.y = source.y;
  3963. this.z = source.z;
  3964. this.w = source.w;
  3965. return this;
  3966. };
  3967. /**
  3968. * Updates the current Vector4 coordinates with the passed floats.
  3969. * Returns the updated Vector4.
  3970. */
  3971. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3972. this.x = x;
  3973. this.y = y;
  3974. this.z = z;
  3975. this.w = w;
  3976. return this;
  3977. };
  3978. /**
  3979. * Updates the current Vector4 coordinates with the passed floats.
  3980. * Returns the updated Vector4.
  3981. */
  3982. Vector4.prototype.set = function (x, y, z, w) {
  3983. return this.copyFromFloats(x, y, z, w);
  3984. };
  3985. // Statics
  3986. /**
  3987. * Returns a new Vector4 set from the starting index of the passed array.
  3988. */
  3989. Vector4.FromArray = function (array, offset) {
  3990. if (!offset) {
  3991. offset = 0;
  3992. }
  3993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3994. };
  3995. /**
  3996. * Updates the passed vector "result" from the starting index of the passed array.
  3997. */
  3998. Vector4.FromArrayToRef = function (array, offset, result) {
  3999. result.x = array[offset];
  4000. result.y = array[offset + 1];
  4001. result.z = array[offset + 2];
  4002. result.w = array[offset + 3];
  4003. };
  4004. /**
  4005. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4006. */
  4007. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4008. Vector4.FromArrayToRef(array, offset, result);
  4009. };
  4010. /**
  4011. * Updates the passed vector "result" coordinates from the passed floats.
  4012. */
  4013. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4014. result.x = x;
  4015. result.y = y;
  4016. result.z = z;
  4017. result.w = w;
  4018. };
  4019. /**
  4020. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4021. */
  4022. Vector4.Zero = function () {
  4023. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4024. };
  4025. /**
  4026. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4027. */
  4028. Vector4.One = function () {
  4029. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4030. };
  4031. /**
  4032. * Returns a new normalized Vector4 from the passed one.
  4033. */
  4034. Vector4.Normalize = function (vector) {
  4035. var result = Vector4.Zero();
  4036. Vector4.NormalizeToRef(vector, result);
  4037. return result;
  4038. };
  4039. /**
  4040. * Updates the passed vector "result" from the normalization of the passed one.
  4041. */
  4042. Vector4.NormalizeToRef = function (vector, result) {
  4043. result.copyFrom(vector);
  4044. result.normalize();
  4045. };
  4046. Vector4.Minimize = function (left, right) {
  4047. var min = left.clone();
  4048. min.minimizeInPlace(right);
  4049. return min;
  4050. };
  4051. Vector4.Maximize = function (left, right) {
  4052. var max = left.clone();
  4053. max.maximizeInPlace(right);
  4054. return max;
  4055. };
  4056. /**
  4057. * Returns the distance (float) between the vectors "value1" and "value2".
  4058. */
  4059. Vector4.Distance = function (value1, value2) {
  4060. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4061. };
  4062. /**
  4063. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4064. */
  4065. Vector4.DistanceSquared = function (value1, value2) {
  4066. var x = value1.x - value2.x;
  4067. var y = value1.y - value2.y;
  4068. var z = value1.z - value2.z;
  4069. var w = value1.w - value2.w;
  4070. return (x * x) + (y * y) + (z * z) + (w * w);
  4071. };
  4072. /**
  4073. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4074. */
  4075. Vector4.Center = function (value1, value2) {
  4076. var center = value1.add(value2);
  4077. center.scaleInPlace(0.5);
  4078. return center;
  4079. };
  4080. /**
  4081. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4082. * This methods computes transformed normalized direction vectors only.
  4083. */
  4084. Vector4.TransformNormal = function (vector, transformation) {
  4085. var result = Vector4.Zero();
  4086. Vector4.TransformNormalToRef(vector, transformation, result);
  4087. return result;
  4088. };
  4089. /**
  4090. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4091. * This methods computes transformed normalized direction vectors only.
  4092. */
  4093. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4094. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4095. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4096. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4097. result.x = x;
  4098. result.y = y;
  4099. result.z = z;
  4100. result.w = vector.w;
  4101. };
  4102. /**
  4103. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4104. * This methods computes transformed normalized direction vectors only.
  4105. */
  4106. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4107. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4108. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4109. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4110. result.w = w;
  4111. };
  4112. return Vector4;
  4113. }());
  4114. BABYLON.Vector4 = Vector4;
  4115. var Size = /** @class */ (function () {
  4116. /**
  4117. * Creates a Size object from the passed width and height (floats).
  4118. */
  4119. function Size(width, height) {
  4120. this.width = width;
  4121. this.height = height;
  4122. }
  4123. // Returns a string with the Size width and height.
  4124. Size.prototype.toString = function () {
  4125. return "{W: " + this.width + ", H: " + this.height + "}";
  4126. };
  4127. /**
  4128. * Returns the string "Size"
  4129. */
  4130. Size.prototype.getClassName = function () {
  4131. return "Size";
  4132. };
  4133. /**
  4134. * Returns the Size hash code.
  4135. */
  4136. Size.prototype.getHashCode = function () {
  4137. var hash = this.width || 0;
  4138. hash = (hash * 397) ^ (this.height || 0);
  4139. return hash;
  4140. };
  4141. /**
  4142. * Updates the current size from the passed one.
  4143. * Returns the updated Size.
  4144. */
  4145. Size.prototype.copyFrom = function (src) {
  4146. this.width = src.width;
  4147. this.height = src.height;
  4148. };
  4149. /**
  4150. * Updates in place the current Size from the passed floats.
  4151. * Returns the updated Size.
  4152. */
  4153. Size.prototype.copyFromFloats = function (width, height) {
  4154. this.width = width;
  4155. this.height = height;
  4156. return this;
  4157. };
  4158. /**
  4159. * Updates in place the current Size from the passed floats.
  4160. * Returns the updated Size.
  4161. */
  4162. Size.prototype.set = function (width, height) {
  4163. return this.copyFromFloats(width, height);
  4164. };
  4165. /**
  4166. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4167. */
  4168. Size.prototype.multiplyByFloats = function (w, h) {
  4169. return new Size(this.width * w, this.height * h);
  4170. };
  4171. /**
  4172. * Returns a new Size copied from the passed one.
  4173. */
  4174. Size.prototype.clone = function () {
  4175. return new Size(this.width, this.height);
  4176. };
  4177. /**
  4178. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4179. */
  4180. Size.prototype.equals = function (other) {
  4181. if (!other) {
  4182. return false;
  4183. }
  4184. return (this.width === other.width) && (this.height === other.height);
  4185. };
  4186. Object.defineProperty(Size.prototype, "surface", {
  4187. /**
  4188. * Returns the surface of the Size : width * height (float).
  4189. */
  4190. get: function () {
  4191. return this.width * this.height;
  4192. },
  4193. enumerable: true,
  4194. configurable: true
  4195. });
  4196. /**
  4197. * Returns a new Size set to (0.0, 0.0)
  4198. */
  4199. Size.Zero = function () {
  4200. return new Size(0.0, 0.0);
  4201. };
  4202. /**
  4203. * Returns a new Size set as the addition result of the current Size and the passed one.
  4204. */
  4205. Size.prototype.add = function (otherSize) {
  4206. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4211. */
  4212. Size.prototype.subtract = function (otherSize) {
  4213. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4214. return r;
  4215. };
  4216. /**
  4217. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4218. */
  4219. Size.Lerp = function (start, end, amount) {
  4220. var w = start.width + ((end.width - start.width) * amount);
  4221. var h = start.height + ((end.height - start.height) * amount);
  4222. return new Size(w, h);
  4223. };
  4224. return Size;
  4225. }());
  4226. BABYLON.Size = Size;
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the passed floats.
  4230. */
  4231. function Quaternion(x, y, z, w) {
  4232. if (x === void 0) { x = 0.0; }
  4233. if (y === void 0) { y = 0.0; }
  4234. if (z === void 0) { z = 0.0; }
  4235. if (w === void 0) { w = 1.0; }
  4236. this.x = x;
  4237. this.y = y;
  4238. this.z = z;
  4239. this.w = w;
  4240. }
  4241. /**
  4242. * Returns a string with the Quaternion coordinates.
  4243. */
  4244. Quaternion.prototype.toString = function () {
  4245. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4246. };
  4247. /**
  4248. * Returns the string "Quaternion".
  4249. */
  4250. Quaternion.prototype.getClassName = function () {
  4251. return "Quaternion";
  4252. };
  4253. /**
  4254. * Returns the Quaternion hash code.
  4255. */
  4256. Quaternion.prototype.getHashCode = function () {
  4257. var hash = this.x || 0;
  4258. hash = (hash * 397) ^ (this.y || 0);
  4259. hash = (hash * 397) ^ (this.z || 0);
  4260. hash = (hash * 397) ^ (this.w || 0);
  4261. return hash;
  4262. };
  4263. /**
  4264. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4265. */
  4266. Quaternion.prototype.asArray = function () {
  4267. return [this.x, this.y, this.z, this.w];
  4268. };
  4269. /**
  4270. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4271. */
  4272. Quaternion.prototype.equals = function (otherQuaternion) {
  4273. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4274. };
  4275. /**
  4276. * Returns a new Quaternion copied from the current one.
  4277. */
  4278. Quaternion.prototype.clone = function () {
  4279. return new Quaternion(this.x, this.y, this.z, this.w);
  4280. };
  4281. /**
  4282. * Updates the current Quaternion from the passed one coordinates.
  4283. * Returns the updated Quaterion.
  4284. */
  4285. Quaternion.prototype.copyFrom = function (other) {
  4286. this.x = other.x;
  4287. this.y = other.y;
  4288. this.z = other.z;
  4289. this.w = other.w;
  4290. return this;
  4291. };
  4292. /**
  4293. * Updates the current Quaternion from the passed float coordinates.
  4294. * Returns the updated Quaterion.
  4295. */
  4296. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4297. this.x = x;
  4298. this.y = y;
  4299. this.z = z;
  4300. this.w = w;
  4301. return this;
  4302. };
  4303. /**
  4304. * Updates the current Quaternion from the passed float coordinates.
  4305. * Returns the updated Quaterion.
  4306. */
  4307. Quaternion.prototype.set = function (x, y, z, w) {
  4308. return this.copyFromFloats(x, y, z, w);
  4309. };
  4310. /**
  4311. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4312. */
  4313. Quaternion.prototype.add = function (other) {
  4314. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4315. };
  4316. /**
  4317. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4318. */
  4319. Quaternion.prototype.subtract = function (other) {
  4320. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4321. };
  4322. /**
  4323. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4324. */
  4325. Quaternion.prototype.scale = function (value) {
  4326. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4327. };
  4328. /**
  4329. * Scale the current Quaternion values by a factor to a given Quaternion
  4330. * @param scale defines the scale factor
  4331. * @param result defines the Quaternion object where to store the result
  4332. * @returns the unmodified current Quaternion
  4333. */
  4334. Quaternion.prototype.scaleToRef = function (scale, result) {
  4335. result.x = this.x * scale;
  4336. result.y = this.y * scale;
  4337. result.z = this.z * scale;
  4338. result.w = this.w * scale;
  4339. return this;
  4340. };
  4341. /**
  4342. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4343. * @param scale defines the scale factor
  4344. * @param result defines the Quaternion object where to store the result
  4345. * @returns the unmodified current Quaternion
  4346. */
  4347. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4348. result.x += this.x * scale;
  4349. result.y += this.y * scale;
  4350. result.z += this.z * scale;
  4351. result.w += this.w * scale;
  4352. return this;
  4353. };
  4354. /**
  4355. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4356. */
  4357. Quaternion.prototype.multiply = function (q1) {
  4358. var result = new Quaternion(0, 0, 0, 1.0);
  4359. this.multiplyToRef(q1, result);
  4360. return result;
  4361. };
  4362. /**
  4363. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4364. * Returns the current Quaternion.
  4365. */
  4366. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4367. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4368. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4369. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4370. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4371. result.copyFromFloats(x, y, z, w);
  4372. return this;
  4373. };
  4374. /**
  4375. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4376. * Returns the updated Quaternion.
  4377. */
  4378. Quaternion.prototype.multiplyInPlace = function (q1) {
  4379. this.multiplyToRef(q1, this);
  4380. return this;
  4381. };
  4382. /**
  4383. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4384. * Returns the current Quaternion.
  4385. */
  4386. Quaternion.prototype.conjugateToRef = function (ref) {
  4387. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4388. return this;
  4389. };
  4390. /**
  4391. * Conjugates in place the current Quaternion.
  4392. * Returns the updated Quaternion.
  4393. */
  4394. Quaternion.prototype.conjugateInPlace = function () {
  4395. this.x *= -1;
  4396. this.y *= -1;
  4397. this.z *= -1;
  4398. return this;
  4399. };
  4400. /**
  4401. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4402. */
  4403. Quaternion.prototype.conjugate = function () {
  4404. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4405. return result;
  4406. };
  4407. /**
  4408. * Returns the Quaternion length (float).
  4409. */
  4410. Quaternion.prototype.length = function () {
  4411. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4412. };
  4413. /**
  4414. * Normalize in place the current Quaternion.
  4415. * Returns the updated Quaternion.
  4416. */
  4417. Quaternion.prototype.normalize = function () {
  4418. var length = 1.0 / this.length();
  4419. this.x *= length;
  4420. this.y *= length;
  4421. this.z *= length;
  4422. this.w *= length;
  4423. return this;
  4424. };
  4425. /**
  4426. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4427. * @param order is a reserved parameter and is ignore for now
  4428. * @returns the new Vector3
  4429. */
  4430. Quaternion.prototype.toEulerAngles = function (order) {
  4431. if (order === void 0) { order = "YZX"; }
  4432. var result = Vector3.Zero();
  4433. this.toEulerAnglesToRef(result, order);
  4434. return result;
  4435. };
  4436. /**
  4437. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4438. * @param result defines the vector which will be filled with the Euler angles
  4439. * @param order is a reserved parameter and is ignore for now
  4440. * @returns the current Quaternion
  4441. */
  4442. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4443. if (order === void 0) { order = "YZX"; }
  4444. var qz = this.z;
  4445. var qx = this.x;
  4446. var qy = this.y;
  4447. var qw = this.w;
  4448. var sqw = qw * qw;
  4449. var sqz = qz * qz;
  4450. var sqx = qx * qx;
  4451. var sqy = qy * qy;
  4452. var zAxisY = qy * qz - qx * qw;
  4453. var limit = .4999999;
  4454. if (zAxisY < -limit) {
  4455. result.y = 2 * Math.atan2(qy, qw);
  4456. result.x = Math.PI / 2;
  4457. result.z = 0;
  4458. }
  4459. else if (zAxisY > limit) {
  4460. result.y = 2 * Math.atan2(qy, qw);
  4461. result.x = -Math.PI / 2;
  4462. result.z = 0;
  4463. }
  4464. else {
  4465. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4466. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4467. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4468. }
  4469. return this;
  4470. };
  4471. /**
  4472. * Updates the passed rotation matrix with the current Quaternion values.
  4473. * Returns the current Quaternion.
  4474. */
  4475. Quaternion.prototype.toRotationMatrix = function (result) {
  4476. var xx = this.x * this.x;
  4477. var yy = this.y * this.y;
  4478. var zz = this.z * this.z;
  4479. var xy = this.x * this.y;
  4480. var zw = this.z * this.w;
  4481. var zx = this.z * this.x;
  4482. var yw = this.y * this.w;
  4483. var yz = this.y * this.z;
  4484. var xw = this.x * this.w;
  4485. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4486. result.m[1] = 2.0 * (xy + zw);
  4487. result.m[2] = 2.0 * (zx - yw);
  4488. result.m[3] = 0;
  4489. result.m[4] = 2.0 * (xy - zw);
  4490. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4491. result.m[6] = 2.0 * (yz + xw);
  4492. result.m[7] = 0;
  4493. result.m[8] = 2.0 * (zx + yw);
  4494. result.m[9] = 2.0 * (yz - xw);
  4495. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4496. result.m[11] = 0;
  4497. result.m[12] = 0;
  4498. result.m[13] = 0;
  4499. result.m[14] = 0;
  4500. result.m[15] = 1.0;
  4501. result._markAsUpdated();
  4502. return this;
  4503. };
  4504. /**
  4505. * Updates the current Quaternion from the passed rotation matrix values.
  4506. * Returns the updated Quaternion.
  4507. */
  4508. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4509. Quaternion.FromRotationMatrixToRef(matrix, this);
  4510. return this;
  4511. };
  4512. // Statics
  4513. /**
  4514. * Returns a new Quaternion set from the passed rotation matrix values.
  4515. */
  4516. Quaternion.FromRotationMatrix = function (matrix) {
  4517. var result = new Quaternion();
  4518. Quaternion.FromRotationMatrixToRef(matrix, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4523. */
  4524. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4525. var data = matrix.m;
  4526. var m11 = data[0], m12 = data[4], m13 = data[8];
  4527. var m21 = data[1], m22 = data[5], m23 = data[9];
  4528. var m31 = data[2], m32 = data[6], m33 = data[10];
  4529. var trace = m11 + m22 + m33;
  4530. var s;
  4531. if (trace > 0) {
  4532. s = 0.5 / Math.sqrt(trace + 1.0);
  4533. result.w = 0.25 / s;
  4534. result.x = (m32 - m23) * s;
  4535. result.y = (m13 - m31) * s;
  4536. result.z = (m21 - m12) * s;
  4537. }
  4538. else if (m11 > m22 && m11 > m33) {
  4539. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4540. result.w = (m32 - m23) / s;
  4541. result.x = 0.25 * s;
  4542. result.y = (m12 + m21) / s;
  4543. result.z = (m13 + m31) / s;
  4544. }
  4545. else if (m22 > m33) {
  4546. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4547. result.w = (m13 - m31) / s;
  4548. result.x = (m12 + m21) / s;
  4549. result.y = 0.25 * s;
  4550. result.z = (m23 + m32) / s;
  4551. }
  4552. else {
  4553. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4554. result.w = (m21 - m12) / s;
  4555. result.x = (m13 + m31) / s;
  4556. result.y = (m23 + m32) / s;
  4557. result.z = 0.25 * s;
  4558. }
  4559. };
  4560. /**
  4561. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4562. */
  4563. Quaternion.Zero = function () {
  4564. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4565. };
  4566. /**
  4567. * Returns a new Quaternion as the inverted current Quaternion.
  4568. */
  4569. Quaternion.Inverse = function (q) {
  4570. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4571. };
  4572. /**
  4573. * Returns the identity Quaternion.
  4574. */
  4575. Quaternion.Identity = function () {
  4576. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4577. };
  4578. Quaternion.IsIdentity = function (quaternion) {
  4579. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4580. };
  4581. /**
  4582. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4583. */
  4584. Quaternion.RotationAxis = function (axis, angle) {
  4585. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4586. };
  4587. /**
  4588. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4589. */
  4590. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4591. var sin = Math.sin(angle / 2);
  4592. axis.normalize();
  4593. result.w = Math.cos(angle / 2);
  4594. result.x = axis.x * sin;
  4595. result.y = axis.y * sin;
  4596. result.z = axis.z * sin;
  4597. return result;
  4598. };
  4599. /**
  4600. * Retuns a new Quaternion set from the starting index of the passed array.
  4601. */
  4602. Quaternion.FromArray = function (array, offset) {
  4603. if (!offset) {
  4604. offset = 0;
  4605. }
  4606. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4607. };
  4608. /**
  4609. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4610. */
  4611. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4612. var q = new Quaternion();
  4613. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4614. return q;
  4615. };
  4616. /**
  4617. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4618. */
  4619. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4620. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4621. var halfRoll = roll * 0.5;
  4622. var halfPitch = pitch * 0.5;
  4623. var halfYaw = yaw * 0.5;
  4624. var sinRoll = Math.sin(halfRoll);
  4625. var cosRoll = Math.cos(halfRoll);
  4626. var sinPitch = Math.sin(halfPitch);
  4627. var cosPitch = Math.cos(halfPitch);
  4628. var sinYaw = Math.sin(halfYaw);
  4629. var cosYaw = Math.cos(halfYaw);
  4630. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4631. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4632. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4633. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4637. */
  4638. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4639. var result = new Quaternion();
  4640. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4641. return result;
  4642. };
  4643. /**
  4644. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4645. */
  4646. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4647. // Produces a quaternion from Euler angles in the z-x-z orientation
  4648. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4649. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4650. var halfBeta = beta * 0.5;
  4651. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4652. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4653. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4654. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4655. };
  4656. /**
  4657. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4658. * cf to Vector3.RotationFromAxis() documentation.
  4659. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4660. */
  4661. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4662. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4663. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4664. return quat;
  4665. };
  4666. /**
  4667. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4668. * cf to Vector3.RotationFromAxis() documentation.
  4669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4670. */
  4671. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4672. var rotMat = MathTmp.Matrix[0];
  4673. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4674. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4675. };
  4676. Quaternion.Slerp = function (left, right, amount) {
  4677. var result = Quaternion.Identity();
  4678. Quaternion.SlerpToRef(left, right, amount, result);
  4679. return result;
  4680. };
  4681. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4682. var num2;
  4683. var num3;
  4684. var num = amount;
  4685. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4686. var flag = false;
  4687. if (num4 < 0) {
  4688. flag = true;
  4689. num4 = -num4;
  4690. }
  4691. if (num4 > 0.999999) {
  4692. num3 = 1 - num;
  4693. num2 = flag ? -num : num;
  4694. }
  4695. else {
  4696. var num5 = Math.acos(num4);
  4697. var num6 = (1.0 / Math.sin(num5));
  4698. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4699. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4700. }
  4701. result.x = (num3 * left.x) + (num2 * right.x);
  4702. result.y = (num3 * left.y) + (num2 * right.y);
  4703. result.z = (num3 * left.z) + (num2 * right.z);
  4704. result.w = (num3 * left.w) + (num2 * right.w);
  4705. };
  4706. /**
  4707. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4708. */
  4709. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4710. var squared = amount * amount;
  4711. var cubed = amount * squared;
  4712. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4713. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4714. var part3 = (cubed - (2.0 * squared)) + amount;
  4715. var part4 = cubed - squared;
  4716. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4717. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4718. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4719. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4720. return new Quaternion(x, y, z, w);
  4721. };
  4722. return Quaternion;
  4723. }());
  4724. BABYLON.Quaternion = Quaternion;
  4725. var Matrix = /** @class */ (function () {
  4726. function Matrix() {
  4727. this._isIdentity = false;
  4728. this._isIdentityDirty = true;
  4729. this.m = new Float32Array(16);
  4730. this._markAsUpdated();
  4731. }
  4732. Matrix.prototype._markAsUpdated = function () {
  4733. this.updateFlag = Matrix._updateFlagSeed++;
  4734. this._isIdentityDirty = true;
  4735. };
  4736. // Properties
  4737. /**
  4738. * Boolean : True is the matrix is the identity matrix
  4739. */
  4740. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4741. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4742. if (this._isIdentityDirty) {
  4743. this._isIdentityDirty = false;
  4744. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4745. this._isIdentity = false;
  4746. }
  4747. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4748. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4749. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4750. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4751. this._isIdentity = false;
  4752. }
  4753. else {
  4754. this._isIdentity = true;
  4755. }
  4756. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4757. this._isIdentity = false;
  4758. }
  4759. }
  4760. return this._isIdentity;
  4761. };
  4762. /**
  4763. * Returns the matrix determinant (float).
  4764. */
  4765. Matrix.prototype.determinant = function () {
  4766. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4767. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4768. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4769. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4770. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4771. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4772. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4773. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4774. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4775. };
  4776. // Methods
  4777. /**
  4778. * Returns the matrix underlying array.
  4779. */
  4780. Matrix.prototype.toArray = function () {
  4781. return this.m;
  4782. };
  4783. /**
  4784. * Returns the matrix underlying array.
  4785. */
  4786. Matrix.prototype.asArray = function () {
  4787. return this.toArray();
  4788. };
  4789. /**
  4790. * Inverts in place the Matrix.
  4791. * Returns the Matrix inverted.
  4792. */
  4793. Matrix.prototype.invert = function () {
  4794. this.invertToRef(this);
  4795. return this;
  4796. };
  4797. /**
  4798. * Sets all the matrix elements to zero.
  4799. * Returns the Matrix.
  4800. */
  4801. Matrix.prototype.reset = function () {
  4802. for (var index = 0; index < 16; index++) {
  4803. this.m[index] = 0.0;
  4804. }
  4805. this._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4810. */
  4811. Matrix.prototype.add = function (other) {
  4812. var result = new Matrix();
  4813. this.addToRef(other, result);
  4814. return result;
  4815. };
  4816. /**
  4817. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4818. * Returns the Matrix.
  4819. */
  4820. Matrix.prototype.addToRef = function (other, result) {
  4821. for (var index = 0; index < 16; index++) {
  4822. result.m[index] = this.m[index] + other.m[index];
  4823. }
  4824. result._markAsUpdated();
  4825. return this;
  4826. };
  4827. /**
  4828. * Adds in place the passed matrix to the current Matrix.
  4829. * Returns the updated Matrix.
  4830. */
  4831. Matrix.prototype.addToSelf = function (other) {
  4832. for (var index = 0; index < 16; index++) {
  4833. this.m[index] += other.m[index];
  4834. }
  4835. this._markAsUpdated();
  4836. return this;
  4837. };
  4838. /**
  4839. * Sets the passed matrix with the current inverted Matrix.
  4840. * Returns the unmodified current Matrix.
  4841. */
  4842. Matrix.prototype.invertToRef = function (other) {
  4843. var l1 = this.m[0];
  4844. var l2 = this.m[1];
  4845. var l3 = this.m[2];
  4846. var l4 = this.m[3];
  4847. var l5 = this.m[4];
  4848. var l6 = this.m[5];
  4849. var l7 = this.m[6];
  4850. var l8 = this.m[7];
  4851. var l9 = this.m[8];
  4852. var l10 = this.m[9];
  4853. var l11 = this.m[10];
  4854. var l12 = this.m[11];
  4855. var l13 = this.m[12];
  4856. var l14 = this.m[13];
  4857. var l15 = this.m[14];
  4858. var l16 = this.m[15];
  4859. var l17 = (l11 * l16) - (l12 * l15);
  4860. var l18 = (l10 * l16) - (l12 * l14);
  4861. var l19 = (l10 * l15) - (l11 * l14);
  4862. var l20 = (l9 * l16) - (l12 * l13);
  4863. var l21 = (l9 * l15) - (l11 * l13);
  4864. var l22 = (l9 * l14) - (l10 * l13);
  4865. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4866. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4867. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4868. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4869. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4870. var l28 = (l7 * l16) - (l8 * l15);
  4871. var l29 = (l6 * l16) - (l8 * l14);
  4872. var l30 = (l6 * l15) - (l7 * l14);
  4873. var l31 = (l5 * l16) - (l8 * l13);
  4874. var l32 = (l5 * l15) - (l7 * l13);
  4875. var l33 = (l5 * l14) - (l6 * l13);
  4876. var l34 = (l7 * l12) - (l8 * l11);
  4877. var l35 = (l6 * l12) - (l8 * l10);
  4878. var l36 = (l6 * l11) - (l7 * l10);
  4879. var l37 = (l5 * l12) - (l8 * l9);
  4880. var l38 = (l5 * l11) - (l7 * l9);
  4881. var l39 = (l5 * l10) - (l6 * l9);
  4882. other.m[0] = l23 * l27;
  4883. other.m[4] = l24 * l27;
  4884. other.m[8] = l25 * l27;
  4885. other.m[12] = l26 * l27;
  4886. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4887. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4888. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4889. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4890. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4891. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4892. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4893. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4894. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4895. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4896. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4897. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4898. other._markAsUpdated();
  4899. return this;
  4900. };
  4901. /**
  4902. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4906. this.m[12] = x;
  4907. this.m[13] = y;
  4908. this.m[14] = z;
  4909. this._markAsUpdated();
  4910. return this;
  4911. };
  4912. /**
  4913. * Inserts the translation vector in the current Matrix.
  4914. * Returns the updated Matrix.
  4915. */
  4916. Matrix.prototype.setTranslation = function (vector3) {
  4917. this.m[12] = vector3.x;
  4918. this.m[13] = vector3.y;
  4919. this.m[14] = vector3.z;
  4920. this._markAsUpdated();
  4921. return this;
  4922. };
  4923. /**
  4924. * Returns a new Vector3 as the extracted translation from the Matrix.
  4925. */
  4926. Matrix.prototype.getTranslation = function () {
  4927. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4928. };
  4929. /**
  4930. * Fill a Vector3 with the extracted translation from the Matrix.
  4931. */
  4932. Matrix.prototype.getTranslationToRef = function (result) {
  4933. result.x = this.m[12];
  4934. result.y = this.m[13];
  4935. result.z = this.m[14];
  4936. return this;
  4937. };
  4938. /**
  4939. * Remove rotation and scaling part from the Matrix.
  4940. * Returns the updated Matrix.
  4941. */
  4942. Matrix.prototype.removeRotationAndScaling = function () {
  4943. this.setRowFromFloats(0, 1, 0, 0, 0);
  4944. this.setRowFromFloats(1, 0, 1, 0, 0);
  4945. this.setRowFromFloats(2, 0, 0, 1, 0);
  4946. return this;
  4947. };
  4948. /**
  4949. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4950. */
  4951. Matrix.prototype.multiply = function (other) {
  4952. var result = new Matrix();
  4953. this.multiplyToRef(other, result);
  4954. return result;
  4955. };
  4956. /**
  4957. * Updates the current Matrix from the passed one values.
  4958. * Returns the updated Matrix.
  4959. */
  4960. Matrix.prototype.copyFrom = function (other) {
  4961. for (var index = 0; index < 16; index++) {
  4962. this.m[index] = other.m[index];
  4963. }
  4964. this._markAsUpdated();
  4965. return this;
  4966. };
  4967. /**
  4968. * Populates the passed array from the starting index with the Matrix values.
  4969. * Returns the Matrix.
  4970. */
  4971. Matrix.prototype.copyToArray = function (array, offset) {
  4972. if (offset === void 0) { offset = 0; }
  4973. for (var index = 0; index < 16; index++) {
  4974. array[offset + index] = this.m[index];
  4975. }
  4976. return this;
  4977. };
  4978. /**
  4979. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4980. */
  4981. Matrix.prototype.multiplyToRef = function (other, result) {
  4982. this.multiplyToArray(other, result.m, 0);
  4983. result._markAsUpdated();
  4984. return this;
  4985. };
  4986. /**
  4987. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4988. */
  4989. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4990. var tm0 = this.m[0];
  4991. var tm1 = this.m[1];
  4992. var tm2 = this.m[2];
  4993. var tm3 = this.m[3];
  4994. var tm4 = this.m[4];
  4995. var tm5 = this.m[5];
  4996. var tm6 = this.m[6];
  4997. var tm7 = this.m[7];
  4998. var tm8 = this.m[8];
  4999. var tm9 = this.m[9];
  5000. var tm10 = this.m[10];
  5001. var tm11 = this.m[11];
  5002. var tm12 = this.m[12];
  5003. var tm13 = this.m[13];
  5004. var tm14 = this.m[14];
  5005. var tm15 = this.m[15];
  5006. var om0 = other.m[0];
  5007. var om1 = other.m[1];
  5008. var om2 = other.m[2];
  5009. var om3 = other.m[3];
  5010. var om4 = other.m[4];
  5011. var om5 = other.m[5];
  5012. var om6 = other.m[6];
  5013. var om7 = other.m[7];
  5014. var om8 = other.m[8];
  5015. var om9 = other.m[9];
  5016. var om10 = other.m[10];
  5017. var om11 = other.m[11];
  5018. var om12 = other.m[12];
  5019. var om13 = other.m[13];
  5020. var om14 = other.m[14];
  5021. var om15 = other.m[15];
  5022. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5023. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5024. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5025. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5026. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5027. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5028. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5029. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5030. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5031. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5032. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5033. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5034. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5035. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5036. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5037. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5038. return this;
  5039. };
  5040. /**
  5041. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5042. */
  5043. Matrix.prototype.equals = function (value) {
  5044. return value &&
  5045. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5046. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5047. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5048. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5049. };
  5050. /**
  5051. * Returns a new Matrix from the current Matrix.
  5052. */
  5053. Matrix.prototype.clone = function () {
  5054. 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]);
  5055. };
  5056. /**
  5057. * Returns the string "Matrix"
  5058. */
  5059. Matrix.prototype.getClassName = function () {
  5060. return "Matrix";
  5061. };
  5062. /**
  5063. * Returns the Matrix hash code.
  5064. */
  5065. Matrix.prototype.getHashCode = function () {
  5066. var hash = this.m[0] || 0;
  5067. for (var i = 1; i < 16; i++) {
  5068. hash = (hash * 397) ^ (this.m[i] || 0);
  5069. }
  5070. return hash;
  5071. };
  5072. /**
  5073. * Decomposes the current Matrix into :
  5074. * - a scale vector3 passed as a reference to update,
  5075. * - a rotation quaternion passed as a reference to update,
  5076. * - a translation vector3 passed as a reference to update.
  5077. * Returns the true if operation was successful.
  5078. */
  5079. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5080. translation.x = this.m[12];
  5081. translation.y = this.m[13];
  5082. translation.z = this.m[14];
  5083. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5084. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5085. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5086. if (this.determinant() <= 0) {
  5087. scale.y *= -1;
  5088. }
  5089. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5090. rotation.x = 0;
  5091. rotation.y = 0;
  5092. rotation.z = 0;
  5093. rotation.w = 1;
  5094. return false;
  5095. }
  5096. 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]);
  5097. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5098. return true;
  5099. };
  5100. /**
  5101. * Returns the index-th row of the current matrix as a new Vector4.
  5102. */
  5103. Matrix.prototype.getRow = function (index) {
  5104. if (index < 0 || index > 3) {
  5105. return null;
  5106. }
  5107. var i = index * 4;
  5108. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5109. };
  5110. /**
  5111. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5112. * Returns the updated Matrix.
  5113. */
  5114. Matrix.prototype.setRow = function (index, row) {
  5115. if (index < 0 || index > 3) {
  5116. return this;
  5117. }
  5118. var i = index * 4;
  5119. this.m[i + 0] = row.x;
  5120. this.m[i + 1] = row.y;
  5121. this.m[i + 2] = row.z;
  5122. this.m[i + 3] = row.w;
  5123. this._markAsUpdated();
  5124. return this;
  5125. };
  5126. /**
  5127. * Compute the transpose of the matrix.
  5128. * Returns a new Matrix.
  5129. */
  5130. Matrix.prototype.transpose = function () {
  5131. return Matrix.Transpose(this);
  5132. };
  5133. /**
  5134. * Compute the transpose of the matrix.
  5135. * Returns the current matrix.
  5136. */
  5137. Matrix.prototype.transposeToRef = function (result) {
  5138. Matrix.TransposeToRef(this, result);
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5143. * Returns the updated Matrix.
  5144. */
  5145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5146. if (index < 0 || index > 3) {
  5147. return this;
  5148. }
  5149. var i = index * 4;
  5150. this.m[i + 0] = x;
  5151. this.m[i + 1] = y;
  5152. this.m[i + 2] = z;
  5153. this.m[i + 3] = w;
  5154. this._markAsUpdated();
  5155. return this;
  5156. };
  5157. /**
  5158. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5159. * @param scale defines the scale factor
  5160. * @returns a new Matrix
  5161. */
  5162. Matrix.prototype.scale = function (scale) {
  5163. var result = new Matrix();
  5164. this.scaleToRef(scale, result);
  5165. return result;
  5166. };
  5167. /**
  5168. * Scale the current Matrix values by a factor to a given result Matrix
  5169. * @param scale defines the scale factor
  5170. * @param result defines the Matrix to store the result
  5171. * @returns the current Matrix
  5172. */
  5173. Matrix.prototype.scaleToRef = function (scale, result) {
  5174. for (var index = 0; index < 16; index++) {
  5175. result.m[index] = this.m[index] * scale;
  5176. }
  5177. result._markAsUpdated();
  5178. return this;
  5179. };
  5180. /**
  5181. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5182. * @param scale defines the scale factor
  5183. * @param result defines the Matrix to store the result
  5184. * @returns the current Matrix
  5185. */
  5186. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5187. for (var index = 0; index < 16; index++) {
  5188. result.m[index] += this.m[index] * scale;
  5189. }
  5190. result._markAsUpdated();
  5191. return this;
  5192. };
  5193. /**
  5194. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5195. * @param ref matrix to store the result
  5196. */
  5197. Matrix.prototype.toNormalMatrix = function (ref) {
  5198. this.invertToRef(ref);
  5199. ref.transpose();
  5200. var m = ref.m;
  5201. 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);
  5202. };
  5203. /**
  5204. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5205. */
  5206. Matrix.prototype.getRotationMatrix = function () {
  5207. var result = Matrix.Identity();
  5208. this.getRotationMatrixToRef(result);
  5209. return result;
  5210. };
  5211. /**
  5212. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5213. * Returns the current Matrix.
  5214. */
  5215. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5216. var m = this.m;
  5217. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5218. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5219. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5220. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5221. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5222. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5223. 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);
  5224. return this;
  5225. };
  5226. // Statics
  5227. /**
  5228. * Returns a new Matrix set from the starting index of the passed array.
  5229. */
  5230. Matrix.FromArray = function (array, offset) {
  5231. var result = new Matrix();
  5232. if (!offset) {
  5233. offset = 0;
  5234. }
  5235. Matrix.FromArrayToRef(array, offset, result);
  5236. return result;
  5237. };
  5238. /**
  5239. * Sets the passed "result" matrix from the starting index of the passed array.
  5240. */
  5241. Matrix.FromArrayToRef = function (array, offset, result) {
  5242. for (var index = 0; index < 16; index++) {
  5243. result.m[index] = array[index + offset];
  5244. }
  5245. result._markAsUpdated();
  5246. };
  5247. /**
  5248. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5249. */
  5250. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5251. for (var index = 0; index < 16; index++) {
  5252. result.m[index] = array[index + offset] * scale;
  5253. }
  5254. result._markAsUpdated();
  5255. };
  5256. /**
  5257. * Sets the passed matrix "result" with the 16 passed floats.
  5258. */
  5259. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5260. result.m[0] = initialM11;
  5261. result.m[1] = initialM12;
  5262. result.m[2] = initialM13;
  5263. result.m[3] = initialM14;
  5264. result.m[4] = initialM21;
  5265. result.m[5] = initialM22;
  5266. result.m[6] = initialM23;
  5267. result.m[7] = initialM24;
  5268. result.m[8] = initialM31;
  5269. result.m[9] = initialM32;
  5270. result.m[10] = initialM33;
  5271. result.m[11] = initialM34;
  5272. result.m[12] = initialM41;
  5273. result.m[13] = initialM42;
  5274. result.m[14] = initialM43;
  5275. result.m[15] = initialM44;
  5276. result._markAsUpdated();
  5277. };
  5278. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5279. /**
  5280. * Static identity matrix to be used as readonly matrix
  5281. * Must not be updated.
  5282. */
  5283. get: function () {
  5284. return Matrix._identityReadOnly;
  5285. },
  5286. enumerable: true,
  5287. configurable: true
  5288. });
  5289. /**
  5290. * Returns a new Matrix set from the 16 passed floats.
  5291. */
  5292. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5293. var result = new Matrix();
  5294. result.m[0] = initialM11;
  5295. result.m[1] = initialM12;
  5296. result.m[2] = initialM13;
  5297. result.m[3] = initialM14;
  5298. result.m[4] = initialM21;
  5299. result.m[5] = initialM22;
  5300. result.m[6] = initialM23;
  5301. result.m[7] = initialM24;
  5302. result.m[8] = initialM31;
  5303. result.m[9] = initialM32;
  5304. result.m[10] = initialM33;
  5305. result.m[11] = initialM34;
  5306. result.m[12] = initialM41;
  5307. result.m[13] = initialM42;
  5308. result.m[14] = initialM43;
  5309. result.m[15] = initialM44;
  5310. return result;
  5311. };
  5312. /**
  5313. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5314. */
  5315. Matrix.Compose = function (scale, rotation, translation) {
  5316. var result = Matrix.Identity();
  5317. Matrix.ComposeToRef(scale, rotation, translation, result);
  5318. return result;
  5319. };
  5320. /**
  5321. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5322. */
  5323. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5324. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5325. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5326. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5327. result.setTranslation(translation);
  5328. };
  5329. /**
  5330. * Returns a new indentity Matrix.
  5331. */
  5332. Matrix.Identity = function () {
  5333. 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);
  5334. };
  5335. /**
  5336. * Sets the passed "result" as an identity matrix.
  5337. */
  5338. Matrix.IdentityToRef = function (result) {
  5339. 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);
  5340. };
  5341. /**
  5342. * Returns a new zero Matrix.
  5343. */
  5344. Matrix.Zero = function () {
  5345. 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);
  5346. };
  5347. /**
  5348. * Returns a new rotation matrix for "angle" radians around the X axis.
  5349. */
  5350. Matrix.RotationX = function (angle) {
  5351. var result = new Matrix();
  5352. Matrix.RotationXToRef(angle, result);
  5353. return result;
  5354. };
  5355. /**
  5356. * Returns a new Matrix as the passed inverted one.
  5357. */
  5358. Matrix.Invert = function (source) {
  5359. var result = new Matrix();
  5360. source.invertToRef(result);
  5361. return result;
  5362. };
  5363. /**
  5364. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5365. */
  5366. Matrix.RotationXToRef = function (angle, result) {
  5367. var s = Math.sin(angle);
  5368. var c = Math.cos(angle);
  5369. result.m[0] = 1.0;
  5370. result.m[15] = 1.0;
  5371. result.m[5] = c;
  5372. result.m[10] = c;
  5373. result.m[9] = -s;
  5374. result.m[6] = s;
  5375. result.m[1] = 0.0;
  5376. result.m[2] = 0.0;
  5377. result.m[3] = 0.0;
  5378. result.m[4] = 0.0;
  5379. result.m[7] = 0.0;
  5380. result.m[8] = 0.0;
  5381. result.m[11] = 0.0;
  5382. result.m[12] = 0.0;
  5383. result.m[13] = 0.0;
  5384. result.m[14] = 0.0;
  5385. result._markAsUpdated();
  5386. };
  5387. /**
  5388. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5389. */
  5390. Matrix.RotationY = function (angle) {
  5391. var result = new Matrix();
  5392. Matrix.RotationYToRef(angle, result);
  5393. return result;
  5394. };
  5395. /**
  5396. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5397. */
  5398. Matrix.RotationYToRef = function (angle, result) {
  5399. var s = Math.sin(angle);
  5400. var c = Math.cos(angle);
  5401. result.m[5] = 1.0;
  5402. result.m[15] = 1.0;
  5403. result.m[0] = c;
  5404. result.m[2] = -s;
  5405. result.m[8] = s;
  5406. result.m[10] = c;
  5407. result.m[1] = 0.0;
  5408. result.m[3] = 0.0;
  5409. result.m[4] = 0.0;
  5410. result.m[6] = 0.0;
  5411. result.m[7] = 0.0;
  5412. result.m[9] = 0.0;
  5413. result.m[11] = 0.0;
  5414. result.m[12] = 0.0;
  5415. result.m[13] = 0.0;
  5416. result.m[14] = 0.0;
  5417. result._markAsUpdated();
  5418. };
  5419. /**
  5420. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5421. */
  5422. Matrix.RotationZ = function (angle) {
  5423. var result = new Matrix();
  5424. Matrix.RotationZToRef(angle, result);
  5425. return result;
  5426. };
  5427. /**
  5428. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5429. */
  5430. Matrix.RotationZToRef = function (angle, result) {
  5431. var s = Math.sin(angle);
  5432. var c = Math.cos(angle);
  5433. result.m[10] = 1.0;
  5434. result.m[15] = 1.0;
  5435. result.m[0] = c;
  5436. result.m[1] = s;
  5437. result.m[4] = -s;
  5438. result.m[5] = c;
  5439. result.m[2] = 0.0;
  5440. result.m[3] = 0.0;
  5441. result.m[6] = 0.0;
  5442. result.m[7] = 0.0;
  5443. result.m[8] = 0.0;
  5444. result.m[9] = 0.0;
  5445. result.m[11] = 0.0;
  5446. result.m[12] = 0.0;
  5447. result.m[13] = 0.0;
  5448. result.m[14] = 0.0;
  5449. result._markAsUpdated();
  5450. };
  5451. /**
  5452. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5453. */
  5454. Matrix.RotationAxis = function (axis, angle) {
  5455. var result = Matrix.Zero();
  5456. Matrix.RotationAxisToRef(axis, angle, result);
  5457. return result;
  5458. };
  5459. /**
  5460. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5461. */
  5462. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5463. var s = Math.sin(-angle);
  5464. var c = Math.cos(-angle);
  5465. var c1 = 1 - c;
  5466. axis.normalize();
  5467. result.m[0] = (axis.x * axis.x) * c1 + c;
  5468. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5469. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5470. result.m[3] = 0.0;
  5471. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5472. result.m[5] = (axis.y * axis.y) * c1 + c;
  5473. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5474. result.m[7] = 0.0;
  5475. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5476. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5477. result.m[10] = (axis.z * axis.z) * c1 + c;
  5478. result.m[11] = 0.0;
  5479. result.m[15] = 1.0;
  5480. result._markAsUpdated();
  5481. };
  5482. /**
  5483. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5484. */
  5485. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5486. var result = new Matrix();
  5487. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5492. */
  5493. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5494. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5495. this._tempQuaternion.toRotationMatrix(result);
  5496. };
  5497. /**
  5498. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5499. */
  5500. Matrix.Scaling = function (x, y, z) {
  5501. var result = Matrix.Zero();
  5502. Matrix.ScalingToRef(x, y, z, result);
  5503. return result;
  5504. };
  5505. /**
  5506. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5507. */
  5508. Matrix.ScalingToRef = function (x, y, z, result) {
  5509. result.m[0] = x;
  5510. result.m[1] = 0.0;
  5511. result.m[2] = 0.0;
  5512. result.m[3] = 0.0;
  5513. result.m[4] = 0.0;
  5514. result.m[5] = y;
  5515. result.m[6] = 0.0;
  5516. result.m[7] = 0.0;
  5517. result.m[8] = 0.0;
  5518. result.m[9] = 0.0;
  5519. result.m[10] = z;
  5520. result.m[11] = 0.0;
  5521. result.m[12] = 0.0;
  5522. result.m[13] = 0.0;
  5523. result.m[14] = 0.0;
  5524. result.m[15] = 1.0;
  5525. result._markAsUpdated();
  5526. };
  5527. /**
  5528. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5529. */
  5530. Matrix.Translation = function (x, y, z) {
  5531. var result = Matrix.Identity();
  5532. Matrix.TranslationToRef(x, y, z, result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5537. */
  5538. Matrix.TranslationToRef = function (x, y, z, result) {
  5539. 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);
  5540. };
  5541. /**
  5542. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5543. * @param startValue defines the start value
  5544. * @param endValue defines the end value
  5545. * @param gradient defines the gradient factor
  5546. * @returns the new matrix
  5547. */
  5548. Matrix.Lerp = function (startValue, endValue, gradient) {
  5549. var result = Matrix.Zero();
  5550. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5551. return result;
  5552. };
  5553. /**
  5554. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5555. * @param startValue defines the start value
  5556. * @param endValue defines the end value
  5557. * @param gradient defines the gradient factor
  5558. * @param result defines the Matrix object where to store data
  5559. */
  5560. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5561. for (var index = 0; index < 16; index++) {
  5562. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5563. }
  5564. result._markAsUpdated();
  5565. };
  5566. /**
  5567. * Returns a new Matrix whose values are computed by :
  5568. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5569. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5570. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5571. */
  5572. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5573. var startScale = new Vector3(0, 0, 0);
  5574. var startRotation = new Quaternion();
  5575. var startTranslation = new Vector3(0, 0, 0);
  5576. startValue.decompose(startScale, startRotation, startTranslation);
  5577. var endScale = new Vector3(0, 0, 0);
  5578. var endRotation = new Quaternion();
  5579. var endTranslation = new Vector3(0, 0, 0);
  5580. endValue.decompose(endScale, endRotation, endTranslation);
  5581. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5582. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5583. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5584. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5585. };
  5586. /**
  5587. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5588. * This methods works for a Left-Handed system.
  5589. */
  5590. Matrix.LookAtLH = function (eye, target, up) {
  5591. var result = Matrix.Zero();
  5592. Matrix.LookAtLHToRef(eye, target, up, result);
  5593. return result;
  5594. };
  5595. /**
  5596. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5597. * This methods works for a Left-Handed system.
  5598. */
  5599. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5600. // Z axis
  5601. target.subtractToRef(eye, this._zAxis);
  5602. this._zAxis.normalize();
  5603. // X axis
  5604. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5605. if (this._xAxis.lengthSquared() === 0) {
  5606. this._xAxis.x = 1.0;
  5607. }
  5608. else {
  5609. this._xAxis.normalize();
  5610. }
  5611. // Y axis
  5612. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5613. this._yAxis.normalize();
  5614. // Eye angles
  5615. var ex = -Vector3.Dot(this._xAxis, eye);
  5616. var ey = -Vector3.Dot(this._yAxis, eye);
  5617. var ez = -Vector3.Dot(this._zAxis, eye);
  5618. 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);
  5619. };
  5620. /**
  5621. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5622. * This methods works for a Right-Handed system.
  5623. */
  5624. Matrix.LookAtRH = function (eye, target, up) {
  5625. var result = Matrix.Zero();
  5626. Matrix.LookAtRHToRef(eye, target, up, result);
  5627. return result;
  5628. };
  5629. /**
  5630. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5631. * This methods works for a Left-Handed system.
  5632. */
  5633. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5634. // Z axis
  5635. eye.subtractToRef(target, this._zAxis);
  5636. this._zAxis.normalize();
  5637. // X axis
  5638. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5639. if (this._xAxis.lengthSquared() === 0) {
  5640. this._xAxis.x = 1.0;
  5641. }
  5642. else {
  5643. this._xAxis.normalize();
  5644. }
  5645. // Y axis
  5646. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5647. this._yAxis.normalize();
  5648. // Eye angles
  5649. var ex = -Vector3.Dot(this._xAxis, eye);
  5650. var ey = -Vector3.Dot(this._yAxis, eye);
  5651. var ez = -Vector3.Dot(this._zAxis, eye);
  5652. 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);
  5653. };
  5654. /**
  5655. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5656. */
  5657. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5658. var matrix = Matrix.Zero();
  5659. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5660. return matrix;
  5661. };
  5662. /**
  5663. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5664. */
  5665. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5666. var n = znear;
  5667. var f = zfar;
  5668. var a = 2.0 / width;
  5669. var b = 2.0 / height;
  5670. var c = 2.0 / (f - n);
  5671. var d = -(f + n) / (f - n);
  5672. 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);
  5673. };
  5674. /**
  5675. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5676. */
  5677. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5678. var matrix = Matrix.Zero();
  5679. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5680. return matrix;
  5681. };
  5682. /**
  5683. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5684. */
  5685. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5686. var n = znear;
  5687. var f = zfar;
  5688. var a = 2.0 / (right - left);
  5689. var b = 2.0 / (top - bottom);
  5690. var c = 2.0 / (f - n);
  5691. var d = -(f + n) / (f - n);
  5692. var i0 = (left + right) / (left - right);
  5693. var i1 = (top + bottom) / (bottom - top);
  5694. 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);
  5695. };
  5696. /**
  5697. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5698. */
  5699. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5700. var matrix = Matrix.Zero();
  5701. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5702. return matrix;
  5703. };
  5704. /**
  5705. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5706. */
  5707. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5708. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5709. result.m[10] *= -1.0;
  5710. };
  5711. /**
  5712. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5713. */
  5714. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5715. var matrix = Matrix.Zero();
  5716. var n = znear;
  5717. var f = zfar;
  5718. var a = 2.0 * n / width;
  5719. var b = 2.0 * n / height;
  5720. var c = (f + n) / (f - n);
  5721. var d = -2.0 * f * n / (f - n);
  5722. 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);
  5723. return matrix;
  5724. };
  5725. /**
  5726. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5727. */
  5728. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5729. var matrix = Matrix.Zero();
  5730. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5731. return matrix;
  5732. };
  5733. /**
  5734. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5735. */
  5736. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5737. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5738. var n = znear;
  5739. var f = zfar;
  5740. var t = 1.0 / (Math.tan(fov * 0.5));
  5741. var a = isVerticalFovFixed ? (t / aspect) : t;
  5742. var b = isVerticalFovFixed ? t : (t * aspect);
  5743. var c = (f + n) / (f - n);
  5744. var d = -2.0 * f * n / (f - n);
  5745. 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);
  5746. };
  5747. /**
  5748. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5749. */
  5750. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5751. var matrix = Matrix.Zero();
  5752. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5753. return matrix;
  5754. };
  5755. /**
  5756. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5757. */
  5758. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5759. //alternatively this could be expressed as:
  5760. // m = PerspectiveFovLHToRef
  5761. // m[10] *= -1.0;
  5762. // m[11] *= -1.0;
  5763. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5764. var n = znear;
  5765. var f = zfar;
  5766. var t = 1.0 / (Math.tan(fov * 0.5));
  5767. var a = isVerticalFovFixed ? (t / aspect) : t;
  5768. var b = isVerticalFovFixed ? t : (t * aspect);
  5769. var c = -(f + n) / (f - n);
  5770. var d = -2 * f * n / (f - n);
  5771. 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);
  5772. };
  5773. /**
  5774. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5775. */
  5776. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5777. if (rightHanded === void 0) { rightHanded = false; }
  5778. var rightHandedFactor = rightHanded ? -1 : 1;
  5779. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5780. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5781. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5782. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5783. var xScale = 2.0 / (leftTan + rightTan);
  5784. var yScale = 2.0 / (upTan + downTan);
  5785. result.m[0] = xScale;
  5786. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5787. result.m[5] = yScale;
  5788. result.m[6] = result.m[7] = 0.0;
  5789. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5790. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5791. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5792. result.m[10] = -zfar / (znear - zfar);
  5793. result.m[11] = 1.0 * rightHandedFactor;
  5794. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5795. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5796. // result.m[14] = (znear * zfar) / (znear - zfar);
  5797. result._markAsUpdated();
  5798. };
  5799. /**
  5800. * Returns the final transformation matrix : world * view * projection * viewport
  5801. */
  5802. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5803. var cw = viewport.width;
  5804. var ch = viewport.height;
  5805. var cx = viewport.x;
  5806. var cy = viewport.y;
  5807. 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);
  5808. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5809. };
  5810. /**
  5811. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5812. */
  5813. Matrix.GetAsMatrix2x2 = function (matrix) {
  5814. return new Float32Array([
  5815. matrix.m[0], matrix.m[1],
  5816. matrix.m[4], matrix.m[5]
  5817. ]);
  5818. };
  5819. /**
  5820. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5821. */
  5822. Matrix.GetAsMatrix3x3 = function (matrix) {
  5823. return new Float32Array([
  5824. matrix.m[0], matrix.m[1], matrix.m[2],
  5825. matrix.m[4], matrix.m[5], matrix.m[6],
  5826. matrix.m[8], matrix.m[9], matrix.m[10]
  5827. ]);
  5828. };
  5829. /**
  5830. * Compute the transpose of the passed Matrix.
  5831. * Returns a new Matrix.
  5832. */
  5833. Matrix.Transpose = function (matrix) {
  5834. var result = new Matrix();
  5835. Matrix.TransposeToRef(matrix, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5840. */
  5841. Matrix.TransposeToRef = function (matrix, result) {
  5842. result.m[0] = matrix.m[0];
  5843. result.m[1] = matrix.m[4];
  5844. result.m[2] = matrix.m[8];
  5845. result.m[3] = matrix.m[12];
  5846. result.m[4] = matrix.m[1];
  5847. result.m[5] = matrix.m[5];
  5848. result.m[6] = matrix.m[9];
  5849. result.m[7] = matrix.m[13];
  5850. result.m[8] = matrix.m[2];
  5851. result.m[9] = matrix.m[6];
  5852. result.m[10] = matrix.m[10];
  5853. result.m[11] = matrix.m[14];
  5854. result.m[12] = matrix.m[3];
  5855. result.m[13] = matrix.m[7];
  5856. result.m[14] = matrix.m[11];
  5857. result.m[15] = matrix.m[15];
  5858. };
  5859. /**
  5860. * Returns a new Matrix as the reflection matrix across the passed plane.
  5861. */
  5862. Matrix.Reflection = function (plane) {
  5863. var matrix = new Matrix();
  5864. Matrix.ReflectionToRef(plane, matrix);
  5865. return matrix;
  5866. };
  5867. /**
  5868. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5869. */
  5870. Matrix.ReflectionToRef = function (plane, result) {
  5871. plane.normalize();
  5872. var x = plane.normal.x;
  5873. var y = plane.normal.y;
  5874. var z = plane.normal.z;
  5875. var temp = -2 * x;
  5876. var temp2 = -2 * y;
  5877. var temp3 = -2 * z;
  5878. result.m[0] = (temp * x) + 1;
  5879. result.m[1] = temp2 * x;
  5880. result.m[2] = temp3 * x;
  5881. result.m[3] = 0.0;
  5882. result.m[4] = temp * y;
  5883. result.m[5] = (temp2 * y) + 1;
  5884. result.m[6] = temp3 * y;
  5885. result.m[7] = 0.0;
  5886. result.m[8] = temp * z;
  5887. result.m[9] = temp2 * z;
  5888. result.m[10] = (temp3 * z) + 1;
  5889. result.m[11] = 0.0;
  5890. result.m[12] = temp * plane.d;
  5891. result.m[13] = temp2 * plane.d;
  5892. result.m[14] = temp3 * plane.d;
  5893. result.m[15] = 1.0;
  5894. result._markAsUpdated();
  5895. };
  5896. /**
  5897. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5898. */
  5899. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5900. result.m[0] = xaxis.x;
  5901. result.m[1] = xaxis.y;
  5902. result.m[2] = xaxis.z;
  5903. result.m[3] = 0.0;
  5904. result.m[4] = yaxis.x;
  5905. result.m[5] = yaxis.y;
  5906. result.m[6] = yaxis.z;
  5907. result.m[7] = 0.0;
  5908. result.m[8] = zaxis.x;
  5909. result.m[9] = zaxis.y;
  5910. result.m[10] = zaxis.z;
  5911. result.m[11] = 0.0;
  5912. result.m[12] = 0.0;
  5913. result.m[13] = 0.0;
  5914. result.m[14] = 0.0;
  5915. result.m[15] = 1.0;
  5916. result._markAsUpdated();
  5917. };
  5918. /**
  5919. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5920. */
  5921. Matrix.FromQuaternionToRef = function (quat, result) {
  5922. var xx = quat.x * quat.x;
  5923. var yy = quat.y * quat.y;
  5924. var zz = quat.z * quat.z;
  5925. var xy = quat.x * quat.y;
  5926. var zw = quat.z * quat.w;
  5927. var zx = quat.z * quat.x;
  5928. var yw = quat.y * quat.w;
  5929. var yz = quat.y * quat.z;
  5930. var xw = quat.x * quat.w;
  5931. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5932. result.m[1] = 2.0 * (xy + zw);
  5933. result.m[2] = 2.0 * (zx - yw);
  5934. result.m[3] = 0.0;
  5935. result.m[4] = 2.0 * (xy - zw);
  5936. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5937. result.m[6] = 2.0 * (yz + xw);
  5938. result.m[7] = 0.0;
  5939. result.m[8] = 2.0 * (zx + yw);
  5940. result.m[9] = 2.0 * (yz - xw);
  5941. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5942. result.m[11] = 0.0;
  5943. result.m[12] = 0.0;
  5944. result.m[13] = 0.0;
  5945. result.m[14] = 0.0;
  5946. result.m[15] = 1.0;
  5947. result._markAsUpdated();
  5948. };
  5949. Matrix._tempQuaternion = new Quaternion();
  5950. Matrix._xAxis = Vector3.Zero();
  5951. Matrix._yAxis = Vector3.Zero();
  5952. Matrix._zAxis = Vector3.Zero();
  5953. Matrix._updateFlagSeed = 0;
  5954. Matrix._identityReadOnly = Matrix.Identity();
  5955. return Matrix;
  5956. }());
  5957. BABYLON.Matrix = Matrix;
  5958. var Plane = /** @class */ (function () {
  5959. /**
  5960. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5961. */
  5962. function Plane(a, b, c, d) {
  5963. this.normal = new Vector3(a, b, c);
  5964. this.d = d;
  5965. }
  5966. /**
  5967. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5968. */
  5969. Plane.prototype.asArray = function () {
  5970. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5971. };
  5972. // Methods
  5973. /**
  5974. * Returns a new plane copied from the current Plane.
  5975. */
  5976. Plane.prototype.clone = function () {
  5977. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5978. };
  5979. /**
  5980. * Returns the string "Plane".
  5981. */
  5982. Plane.prototype.getClassName = function () {
  5983. return "Plane";
  5984. };
  5985. /**
  5986. * Returns the Plane hash code.
  5987. */
  5988. Plane.prototype.getHashCode = function () {
  5989. var hash = this.normal.getHashCode();
  5990. hash = (hash * 397) ^ (this.d || 0);
  5991. return hash;
  5992. };
  5993. /**
  5994. * Normalize the current Plane in place.
  5995. * Returns the updated Plane.
  5996. */
  5997. Plane.prototype.normalize = function () {
  5998. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5999. var magnitude = 0.0;
  6000. if (norm !== 0) {
  6001. magnitude = 1.0 / norm;
  6002. }
  6003. this.normal.x *= magnitude;
  6004. this.normal.y *= magnitude;
  6005. this.normal.z *= magnitude;
  6006. this.d *= magnitude;
  6007. return this;
  6008. };
  6009. /**
  6010. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6011. */
  6012. Plane.prototype.transform = function (transformation) {
  6013. var transposedMatrix = Matrix.Transpose(transformation);
  6014. var x = this.normal.x;
  6015. var y = this.normal.y;
  6016. var z = this.normal.z;
  6017. var d = this.d;
  6018. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6019. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6020. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6021. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6022. return new Plane(normalX, normalY, normalZ, finalD);
  6023. };
  6024. /**
  6025. * Returns the dot product (float) of the point coordinates and the plane normal.
  6026. */
  6027. Plane.prototype.dotCoordinate = function (point) {
  6028. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6029. };
  6030. /**
  6031. * Updates the current Plane from the plane defined by the three passed points.
  6032. * Returns the updated Plane.
  6033. */
  6034. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6035. var x1 = point2.x - point1.x;
  6036. var y1 = point2.y - point1.y;
  6037. var z1 = point2.z - point1.z;
  6038. var x2 = point3.x - point1.x;
  6039. var y2 = point3.y - point1.y;
  6040. var z2 = point3.z - point1.z;
  6041. var yz = (y1 * z2) - (z1 * y2);
  6042. var xz = (z1 * x2) - (x1 * z2);
  6043. var xy = (x1 * y2) - (y1 * x2);
  6044. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6045. var invPyth;
  6046. if (pyth !== 0) {
  6047. invPyth = 1.0 / pyth;
  6048. }
  6049. else {
  6050. invPyth = 0.0;
  6051. }
  6052. this.normal.x = yz * invPyth;
  6053. this.normal.y = xz * invPyth;
  6054. this.normal.z = xy * invPyth;
  6055. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6056. return this;
  6057. };
  6058. /**
  6059. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6060. */
  6061. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6062. var dot = Vector3.Dot(this.normal, direction);
  6063. return (dot <= epsilon);
  6064. };
  6065. /**
  6066. * Returns the signed distance (float) from the passed point to the Plane.
  6067. */
  6068. Plane.prototype.signedDistanceTo = function (point) {
  6069. return Vector3.Dot(point, this.normal) + this.d;
  6070. };
  6071. // Statics
  6072. /**
  6073. * Returns a new Plane from the passed array.
  6074. */
  6075. Plane.FromArray = function (array) {
  6076. return new Plane(array[0], array[1], array[2], array[3]);
  6077. };
  6078. /**
  6079. * Returns a new Plane defined by the three passed points.
  6080. */
  6081. Plane.FromPoints = function (point1, point2, point3) {
  6082. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6083. result.copyFromPoints(point1, point2, point3);
  6084. return result;
  6085. };
  6086. /**
  6087. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6088. * Note : the vector "normal" is updated because normalized.
  6089. */
  6090. Plane.FromPositionAndNormal = function (origin, normal) {
  6091. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6092. normal.normalize();
  6093. result.normal = normal;
  6094. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6095. return result;
  6096. };
  6097. /**
  6098. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6099. */
  6100. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6101. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6102. return Vector3.Dot(point, normal) + d;
  6103. };
  6104. return Plane;
  6105. }());
  6106. BABYLON.Plane = Plane;
  6107. var Viewport = /** @class */ (function () {
  6108. /**
  6109. * Creates a Viewport object located at (x, y) and sized (width, height).
  6110. */
  6111. function Viewport(x, y, width, height) {
  6112. this.x = x;
  6113. this.y = y;
  6114. this.width = width;
  6115. this.height = height;
  6116. }
  6117. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6118. if (renderWidthOrEngine.getRenderWidth) {
  6119. var engine = renderWidthOrEngine;
  6120. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6121. }
  6122. var renderWidth = renderWidthOrEngine;
  6123. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6124. };
  6125. /**
  6126. * Returns a new Viewport copied from the current one.
  6127. */
  6128. Viewport.prototype.clone = function () {
  6129. return new Viewport(this.x, this.y, this.width, this.height);
  6130. };
  6131. return Viewport;
  6132. }());
  6133. BABYLON.Viewport = Viewport;
  6134. var Frustum = /** @class */ (function () {
  6135. function Frustum() {
  6136. }
  6137. /**
  6138. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6139. */
  6140. Frustum.GetPlanes = function (transform) {
  6141. var frustumPlanes = [];
  6142. for (var index = 0; index < 6; index++) {
  6143. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6144. }
  6145. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6146. return frustumPlanes;
  6147. };
  6148. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6149. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6150. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6151. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6152. frustumPlane.d = transform.m[15] + transform.m[14];
  6153. frustumPlane.normalize();
  6154. };
  6155. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6156. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6157. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6158. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6159. frustumPlane.d = transform.m[15] - transform.m[14];
  6160. frustumPlane.normalize();
  6161. };
  6162. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6163. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6164. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6165. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6166. frustumPlane.d = transform.m[15] + transform.m[12];
  6167. frustumPlane.normalize();
  6168. };
  6169. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6170. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6171. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6172. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6173. frustumPlane.d = transform.m[15] - transform.m[12];
  6174. frustumPlane.normalize();
  6175. };
  6176. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6177. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6178. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6179. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6180. frustumPlane.d = transform.m[15] - transform.m[13];
  6181. frustumPlane.normalize();
  6182. };
  6183. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6184. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6185. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6186. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6187. frustumPlane.d = transform.m[15] + transform.m[13];
  6188. frustumPlane.normalize();
  6189. };
  6190. /**
  6191. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6192. */
  6193. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6194. // Near
  6195. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6196. // Far
  6197. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6198. // Left
  6199. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6200. // Right
  6201. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6202. // Top
  6203. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6204. // Bottom
  6205. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6206. };
  6207. return Frustum;
  6208. }());
  6209. BABYLON.Frustum = Frustum;
  6210. var Space;
  6211. (function (Space) {
  6212. Space[Space["LOCAL"] = 0] = "LOCAL";
  6213. Space[Space["WORLD"] = 1] = "WORLD";
  6214. Space[Space["BONE"] = 2] = "BONE";
  6215. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6216. var Axis = /** @class */ (function () {
  6217. function Axis() {
  6218. }
  6219. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6220. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6221. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6222. return Axis;
  6223. }());
  6224. BABYLON.Axis = Axis;
  6225. ;
  6226. var BezierCurve = /** @class */ (function () {
  6227. function BezierCurve() {
  6228. }
  6229. /**
  6230. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6231. */
  6232. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6233. // Extract X (which is equal to time here)
  6234. var f0 = 1 - 3 * x2 + 3 * x1;
  6235. var f1 = 3 * x2 - 6 * x1;
  6236. var f2 = 3 * x1;
  6237. var refinedT = t;
  6238. for (var i = 0; i < 5; i++) {
  6239. var refinedT2 = refinedT * refinedT;
  6240. var refinedT3 = refinedT2 * refinedT;
  6241. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6242. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6243. refinedT -= (x - t) * slope;
  6244. refinedT = Math.min(1, Math.max(0, refinedT));
  6245. }
  6246. // Resolve cubic bezier for the given x
  6247. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6248. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6249. Math.pow(refinedT, 3);
  6250. };
  6251. return BezierCurve;
  6252. }());
  6253. BABYLON.BezierCurve = BezierCurve;
  6254. var Orientation;
  6255. (function (Orientation) {
  6256. Orientation[Orientation["CW"] = 0] = "CW";
  6257. Orientation[Orientation["CCW"] = 1] = "CCW";
  6258. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6259. var Angle = /** @class */ (function () {
  6260. /**
  6261. * Creates an Angle object of "radians" radians (float).
  6262. */
  6263. function Angle(radians) {
  6264. var _this = this;
  6265. /**
  6266. * Returns the Angle value in degrees (float).
  6267. */
  6268. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6269. /**
  6270. * Returns the Angle value in radians (float).
  6271. */
  6272. this.radians = function () { return _this._radians; };
  6273. this._radians = radians;
  6274. if (this._radians < 0.0)
  6275. this._radians += (2.0 * Math.PI);
  6276. }
  6277. /**
  6278. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6279. */
  6280. Angle.BetweenTwoPoints = function (a, b) {
  6281. var delta = b.subtract(a);
  6282. var theta = Math.atan2(delta.y, delta.x);
  6283. return new Angle(theta);
  6284. };
  6285. /**
  6286. * Returns a new Angle object from the passed float in radians.
  6287. */
  6288. Angle.FromRadians = function (radians) {
  6289. return new Angle(radians);
  6290. };
  6291. /**
  6292. * Returns a new Angle object from the passed float in degrees.
  6293. */
  6294. Angle.FromDegrees = function (degrees) {
  6295. return new Angle(degrees * Math.PI / 180.0);
  6296. };
  6297. return Angle;
  6298. }());
  6299. BABYLON.Angle = Angle;
  6300. var Arc2 = /** @class */ (function () {
  6301. /**
  6302. * Creates an Arc object from the three passed points : start, middle and end.
  6303. */
  6304. function Arc2(startPoint, midPoint, endPoint) {
  6305. this.startPoint = startPoint;
  6306. this.midPoint = midPoint;
  6307. this.endPoint = endPoint;
  6308. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6309. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6310. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6311. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6312. 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);
  6313. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6314. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6315. var a1 = this.startAngle.degrees();
  6316. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6317. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6318. // angles correction
  6319. if (a2 - a1 > +180.0)
  6320. a2 -= 360.0;
  6321. if (a2 - a1 < -180.0)
  6322. a2 += 360.0;
  6323. if (a3 - a2 > +180.0)
  6324. a3 -= 360.0;
  6325. if (a3 - a2 < -180.0)
  6326. a3 += 360.0;
  6327. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6328. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6329. }
  6330. return Arc2;
  6331. }());
  6332. BABYLON.Arc2 = Arc2;
  6333. var Path2 = /** @class */ (function () {
  6334. /**
  6335. * Creates a Path2 object from the starting 2D coordinates x and y.
  6336. */
  6337. function Path2(x, y) {
  6338. this._points = new Array();
  6339. this._length = 0.0;
  6340. this.closed = false;
  6341. this._points.push(new Vector2(x, y));
  6342. }
  6343. /**
  6344. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6345. * Returns the updated Path2.
  6346. */
  6347. Path2.prototype.addLineTo = function (x, y) {
  6348. if (this.closed) {
  6349. return this;
  6350. }
  6351. var newPoint = new Vector2(x, y);
  6352. var previousPoint = this._points[this._points.length - 1];
  6353. this._points.push(newPoint);
  6354. this._length += newPoint.subtract(previousPoint).length();
  6355. return this;
  6356. };
  6357. /**
  6358. * 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.
  6359. * Returns the updated Path2.
  6360. */
  6361. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6362. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6363. if (this.closed) {
  6364. return this;
  6365. }
  6366. var startPoint = this._points[this._points.length - 1];
  6367. var midPoint = new Vector2(midX, midY);
  6368. var endPoint = new Vector2(endX, endY);
  6369. var arc = new Arc2(startPoint, midPoint, endPoint);
  6370. var increment = arc.angle.radians() / numberOfSegments;
  6371. if (arc.orientation === Orientation.CW)
  6372. increment *= -1;
  6373. var currentAngle = arc.startAngle.radians() + increment;
  6374. for (var i = 0; i < numberOfSegments; i++) {
  6375. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6376. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6377. this.addLineTo(x, y);
  6378. currentAngle += increment;
  6379. }
  6380. return this;
  6381. };
  6382. /**
  6383. * Closes the Path2.
  6384. * Returns the Path2.
  6385. */
  6386. Path2.prototype.close = function () {
  6387. this.closed = true;
  6388. return this;
  6389. };
  6390. /**
  6391. * Returns the Path2 total length (float).
  6392. */
  6393. Path2.prototype.length = function () {
  6394. var result = this._length;
  6395. if (!this.closed) {
  6396. var lastPoint = this._points[this._points.length - 1];
  6397. var firstPoint = this._points[0];
  6398. result += (firstPoint.subtract(lastPoint).length());
  6399. }
  6400. return result;
  6401. };
  6402. /**
  6403. * Returns the Path2 internal array of points.
  6404. */
  6405. Path2.prototype.getPoints = function () {
  6406. return this._points;
  6407. };
  6408. /**
  6409. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6410. */
  6411. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6412. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6413. return Vector2.Zero();
  6414. }
  6415. var lengthPosition = normalizedLengthPosition * this.length();
  6416. var previousOffset = 0;
  6417. for (var i = 0; i < this._points.length; i++) {
  6418. var j = (i + 1) % this._points.length;
  6419. var a = this._points[i];
  6420. var b = this._points[j];
  6421. var bToA = b.subtract(a);
  6422. var nextOffset = (bToA.length() + previousOffset);
  6423. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6424. var dir = bToA.normalize();
  6425. var localOffset = lengthPosition - previousOffset;
  6426. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6427. }
  6428. previousOffset = nextOffset;
  6429. }
  6430. return Vector2.Zero();
  6431. };
  6432. /**
  6433. * Returns a new Path2 starting at the coordinates (x, y).
  6434. */
  6435. Path2.StartingAt = function (x, y) {
  6436. return new Path2(x, y);
  6437. };
  6438. return Path2;
  6439. }());
  6440. BABYLON.Path2 = Path2;
  6441. var Path3D = /** @class */ (function () {
  6442. /**
  6443. * new Path3D(path, normal, raw)
  6444. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6445. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6446. * path : an array of Vector3, the curve axis of the Path3D
  6447. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6448. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6449. */
  6450. function Path3D(path, firstNormal, raw) {
  6451. if (firstNormal === void 0) { firstNormal = null; }
  6452. this.path = path;
  6453. this._curve = new Array();
  6454. this._distances = new Array();
  6455. this._tangents = new Array();
  6456. this._normals = new Array();
  6457. this._binormals = new Array();
  6458. for (var p = 0; p < path.length; p++) {
  6459. this._curve[p] = path[p].clone(); // hard copy
  6460. }
  6461. this._raw = raw || false;
  6462. this._compute(firstNormal);
  6463. }
  6464. /**
  6465. * Returns the Path3D array of successive Vector3 designing its curve.
  6466. */
  6467. Path3D.prototype.getCurve = function () {
  6468. return this._curve;
  6469. };
  6470. /**
  6471. * Returns an array populated with tangent vectors on each Path3D curve point.
  6472. */
  6473. Path3D.prototype.getTangents = function () {
  6474. return this._tangents;
  6475. };
  6476. /**
  6477. * Returns an array populated with normal vectors on each Path3D curve point.
  6478. */
  6479. Path3D.prototype.getNormals = function () {
  6480. return this._normals;
  6481. };
  6482. /**
  6483. * Returns an array populated with binormal vectors on each Path3D curve point.
  6484. */
  6485. Path3D.prototype.getBinormals = function () {
  6486. return this._binormals;
  6487. };
  6488. /**
  6489. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6490. */
  6491. Path3D.prototype.getDistances = function () {
  6492. return this._distances;
  6493. };
  6494. /**
  6495. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6496. * Returns the same object updated.
  6497. */
  6498. Path3D.prototype.update = function (path, firstNormal) {
  6499. if (firstNormal === void 0) { firstNormal = null; }
  6500. for (var p = 0; p < path.length; p++) {
  6501. this._curve[p].x = path[p].x;
  6502. this._curve[p].y = path[p].y;
  6503. this._curve[p].z = path[p].z;
  6504. }
  6505. this._compute(firstNormal);
  6506. return this;
  6507. };
  6508. // private function compute() : computes tangents, normals and binormals
  6509. Path3D.prototype._compute = function (firstNormal) {
  6510. var l = this._curve.length;
  6511. // first and last tangents
  6512. this._tangents[0] = this._getFirstNonNullVector(0);
  6513. if (!this._raw) {
  6514. this._tangents[0].normalize();
  6515. }
  6516. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6517. if (!this._raw) {
  6518. this._tangents[l - 1].normalize();
  6519. }
  6520. // normals and binormals at first point : arbitrary vector with _normalVector()
  6521. var tg0 = this._tangents[0];
  6522. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6523. this._normals[0] = pp0;
  6524. if (!this._raw) {
  6525. this._normals[0].normalize();
  6526. }
  6527. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6528. if (!this._raw) {
  6529. this._binormals[0].normalize();
  6530. }
  6531. this._distances[0] = 0.0;
  6532. // normals and binormals : next points
  6533. var prev; // previous vector (segment)
  6534. var cur; // current vector (segment)
  6535. var curTang; // current tangent
  6536. // previous normal
  6537. var prevBinor; // previous binormal
  6538. for (var i = 1; i < l; i++) {
  6539. // tangents
  6540. prev = this._getLastNonNullVector(i);
  6541. if (i < l - 1) {
  6542. cur = this._getFirstNonNullVector(i);
  6543. this._tangents[i] = prev.add(cur);
  6544. this._tangents[i].normalize();
  6545. }
  6546. this._distances[i] = this._distances[i - 1] + prev.length();
  6547. // normals and binormals
  6548. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6549. curTang = this._tangents[i];
  6550. prevBinor = this._binormals[i - 1];
  6551. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6552. if (!this._raw) {
  6553. this._normals[i].normalize();
  6554. }
  6555. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6556. if (!this._raw) {
  6557. this._binormals[i].normalize();
  6558. }
  6559. }
  6560. };
  6561. // private function getFirstNonNullVector(index)
  6562. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6563. Path3D.prototype._getFirstNonNullVector = function (index) {
  6564. var i = 1;
  6565. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6566. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6567. i++;
  6568. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6569. }
  6570. return nNVector;
  6571. };
  6572. // private function getLastNonNullVector(index)
  6573. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6574. Path3D.prototype._getLastNonNullVector = function (index) {
  6575. var i = 1;
  6576. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6577. while (nLVector.length() === 0 && index > i + 1) {
  6578. i++;
  6579. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6580. }
  6581. return nLVector;
  6582. };
  6583. // private function normalVector(v0, vt, va) :
  6584. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6585. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6586. Path3D.prototype._normalVector = function (v0, vt, va) {
  6587. var normal0;
  6588. var tgl = vt.length();
  6589. if (tgl === 0.0) {
  6590. tgl = 1.0;
  6591. }
  6592. if (va === undefined || va === null) {
  6593. var point;
  6594. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6595. point = new Vector3(0.0, -1.0, 0.0);
  6596. }
  6597. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6598. point = new Vector3(1.0, 0.0, 0.0);
  6599. }
  6600. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6601. point = new Vector3(0.0, 0.0, 1.0);
  6602. }
  6603. else {
  6604. point = Vector3.Zero();
  6605. }
  6606. normal0 = Vector3.Cross(vt, point);
  6607. }
  6608. else {
  6609. normal0 = Vector3.Cross(vt, va);
  6610. Vector3.CrossToRef(normal0, vt, normal0);
  6611. }
  6612. normal0.normalize();
  6613. return normal0;
  6614. };
  6615. return Path3D;
  6616. }());
  6617. BABYLON.Path3D = Path3D;
  6618. var Curve3 = /** @class */ (function () {
  6619. /**
  6620. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6621. * A Curve3 is designed from a series of successive Vector3.
  6622. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6623. */
  6624. function Curve3(points) {
  6625. this._length = 0.0;
  6626. this._points = points;
  6627. this._length = this._computeLength(points);
  6628. }
  6629. /**
  6630. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6631. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6632. * @param v1 (Vector3) the control point
  6633. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6634. * @param nbPoints (integer) the wanted number of points in the curve
  6635. */
  6636. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6637. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6638. var bez = new Array();
  6639. var equation = function (t, val0, val1, val2) {
  6640. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6641. return res;
  6642. };
  6643. for (var i = 0; i <= nbPoints; i++) {
  6644. 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)));
  6645. }
  6646. return new Curve3(bez);
  6647. };
  6648. /**
  6649. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6650. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6651. * @param v1 (Vector3) the first control point
  6652. * @param v2 (Vector3) the second control point
  6653. * @param v3 (Vector3) the end point of the Cubic Bezier
  6654. * @param nbPoints (integer) the wanted number of points in the curve
  6655. */
  6656. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6657. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6658. var bez = new Array();
  6659. var equation = function (t, val0, val1, val2, val3) {
  6660. 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;
  6661. return res;
  6662. };
  6663. for (var i = 0; i <= nbPoints; i++) {
  6664. 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)));
  6665. }
  6666. return new Curve3(bez);
  6667. };
  6668. /**
  6669. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6670. * @param p1 (Vector3) the origin point of the Hermite Spline
  6671. * @param t1 (Vector3) the tangent vector at the origin point
  6672. * @param p2 (Vector3) the end point of the Hermite Spline
  6673. * @param t2 (Vector3) the tangent vector at the end point
  6674. * @param nbPoints (integer) the wanted number of points in the curve
  6675. */
  6676. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6677. var hermite = new Array();
  6678. var step = 1.0 / nbPoints;
  6679. for (var i = 0; i <= nbPoints; i++) {
  6680. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6681. }
  6682. return new Curve3(hermite);
  6683. };
  6684. /**
  6685. * Returns a Curve3 object along a CatmullRom Spline curve :
  6686. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6687. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6688. */
  6689. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6690. var totalPoints = new Array();
  6691. totalPoints.push(points[0].clone());
  6692. Array.prototype.push.apply(totalPoints, points);
  6693. totalPoints.push(points[points.length - 1].clone());
  6694. var catmullRom = new Array();
  6695. var step = 1.0 / nbPoints;
  6696. var amount = 0.0;
  6697. for (var i = 0; i < totalPoints.length - 3; i++) {
  6698. amount = 0;
  6699. for (var c = 0; c < nbPoints; c++) {
  6700. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6701. amount += step;
  6702. }
  6703. }
  6704. i--;
  6705. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6706. return new Curve3(catmullRom);
  6707. };
  6708. /**
  6709. * Returns the Curve3 stored array of successive Vector3
  6710. */
  6711. Curve3.prototype.getPoints = function () {
  6712. return this._points;
  6713. };
  6714. /**
  6715. * Returns the computed length (float) of the curve.
  6716. */
  6717. Curve3.prototype.length = function () {
  6718. return this._length;
  6719. };
  6720. /**
  6721. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6722. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6723. * curveA and curveB keep unchanged.
  6724. */
  6725. Curve3.prototype.continue = function (curve) {
  6726. var lastPoint = this._points[this._points.length - 1];
  6727. var continuedPoints = this._points.slice();
  6728. var curvePoints = curve.getPoints();
  6729. for (var i = 1; i < curvePoints.length; i++) {
  6730. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6731. }
  6732. var continuedCurve = new Curve3(continuedPoints);
  6733. return continuedCurve;
  6734. };
  6735. Curve3.prototype._computeLength = function (path) {
  6736. var l = 0;
  6737. for (var i = 1; i < path.length; i++) {
  6738. l += (path[i].subtract(path[i - 1])).length();
  6739. }
  6740. return l;
  6741. };
  6742. return Curve3;
  6743. }());
  6744. BABYLON.Curve3 = Curve3;
  6745. // Vertex formats
  6746. var PositionNormalVertex = /** @class */ (function () {
  6747. function PositionNormalVertex(position, normal) {
  6748. if (position === void 0) { position = Vector3.Zero(); }
  6749. if (normal === void 0) { normal = Vector3.Up(); }
  6750. this.position = position;
  6751. this.normal = normal;
  6752. }
  6753. PositionNormalVertex.prototype.clone = function () {
  6754. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6755. };
  6756. return PositionNormalVertex;
  6757. }());
  6758. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6759. var PositionNormalTextureVertex = /** @class */ (function () {
  6760. function PositionNormalTextureVertex(position, normal, uv) {
  6761. if (position === void 0) { position = Vector3.Zero(); }
  6762. if (normal === void 0) { normal = Vector3.Up(); }
  6763. if (uv === void 0) { uv = Vector2.Zero(); }
  6764. this.position = position;
  6765. this.normal = normal;
  6766. this.uv = uv;
  6767. }
  6768. PositionNormalTextureVertex.prototype.clone = function () {
  6769. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6770. };
  6771. return PositionNormalTextureVertex;
  6772. }());
  6773. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6774. // Temporary pre-allocated objects for engine internal use
  6775. // usage in any internal function :
  6776. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6777. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6778. var Tmp = /** @class */ (function () {
  6779. function Tmp() {
  6780. }
  6781. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6782. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6783. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6784. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6785. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6786. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6787. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6788. Matrix.Zero(), Matrix.Zero(),
  6789. Matrix.Zero(), Matrix.Zero(),
  6790. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6791. return Tmp;
  6792. }());
  6793. BABYLON.Tmp = Tmp;
  6794. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6795. var MathTmp = /** @class */ (function () {
  6796. function MathTmp() {
  6797. }
  6798. MathTmp.Vector3 = [Vector3.Zero()];
  6799. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6800. MathTmp.Quaternion = [Quaternion.Zero()];
  6801. return MathTmp;
  6802. }());
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.math.js.map
  6805. "use strict";
  6806. var BABYLON;
  6807. (function (BABYLON) {
  6808. var Scalar = /** @class */ (function () {
  6809. function Scalar() {
  6810. }
  6811. /**
  6812. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6813. */
  6814. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6815. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6816. var num = a - b;
  6817. return -epsilon <= num && num <= epsilon;
  6818. };
  6819. /**
  6820. * Returns a string : the upper case translation of the number i to hexadecimal.
  6821. */
  6822. Scalar.ToHex = function (i) {
  6823. var str = i.toString(16);
  6824. if (i <= 15) {
  6825. return ("0" + str).toUpperCase();
  6826. }
  6827. return str.toUpperCase();
  6828. };
  6829. /**
  6830. * Returns -1 if value is negative and +1 is value is positive.
  6831. * Returns the value itself if it's equal to zero.
  6832. */
  6833. Scalar.Sign = function (value) {
  6834. value = +value; // convert to a number
  6835. if (value === 0 || isNaN(value))
  6836. return value;
  6837. return value > 0 ? 1 : -1;
  6838. };
  6839. /**
  6840. * Returns the value itself if it's between min and max.
  6841. * Returns min if the value is lower than min.
  6842. * Returns max if the value is greater than max.
  6843. */
  6844. Scalar.Clamp = function (value, min, max) {
  6845. if (min === void 0) { min = 0; }
  6846. if (max === void 0) { max = 1; }
  6847. return Math.min(max, Math.max(min, value));
  6848. };
  6849. /**
  6850. * Returns the log2 of value.
  6851. */
  6852. Scalar.Log2 = function (value) {
  6853. return Math.log(value) * Math.LOG2E;
  6854. };
  6855. /**
  6856. * Loops the value, so that it is never larger than length and never smaller than 0.
  6857. *
  6858. * This is similar to the modulo operator but it works with floating point numbers.
  6859. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6860. * With t = 5 and length = 2.5, the result would be 0.0.
  6861. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6862. */
  6863. Scalar.Repeat = function (value, length) {
  6864. return value - Math.floor(value / length) * length;
  6865. };
  6866. /**
  6867. * Normalize the value between 0.0 and 1.0 using min and max values
  6868. */
  6869. Scalar.Normalize = function (value, min, max) {
  6870. return (value - min) / (max - min);
  6871. };
  6872. /**
  6873. * Denormalize the value from 0.0 and 1.0 using min and max values
  6874. */
  6875. Scalar.Denormalize = function (normalized, min, max) {
  6876. return (normalized * (max - min) + min);
  6877. };
  6878. /**
  6879. * Calculates the shortest difference between two given angles given in degrees.
  6880. */
  6881. Scalar.DeltaAngle = function (current, target) {
  6882. var num = Scalar.Repeat(target - current, 360.0);
  6883. if (num > 180.0) {
  6884. num -= 360.0;
  6885. }
  6886. return num;
  6887. };
  6888. /**
  6889. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6890. *
  6891. * The returned value will move back and forth between 0 and length
  6892. */
  6893. Scalar.PingPong = function (tx, length) {
  6894. var t = Scalar.Repeat(tx, length * 2.0);
  6895. return length - Math.abs(t - length);
  6896. };
  6897. /**
  6898. * Interpolates between min and max with smoothing at the limits.
  6899. *
  6900. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6901. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6902. */
  6903. Scalar.SmoothStep = function (from, to, tx) {
  6904. var t = Scalar.Clamp(tx);
  6905. t = -2.0 * t * t * t + 3.0 * t * t;
  6906. return to * t + from * (1.0 - t);
  6907. };
  6908. /**
  6909. * Moves a value current towards target.
  6910. *
  6911. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6912. * Negative values of maxDelta pushes the value away from target.
  6913. */
  6914. Scalar.MoveTowards = function (current, target, maxDelta) {
  6915. var result = 0;
  6916. if (Math.abs(target - current) <= maxDelta) {
  6917. result = target;
  6918. }
  6919. else {
  6920. result = current + Scalar.Sign(target - current) * maxDelta;
  6921. }
  6922. return result;
  6923. };
  6924. /**
  6925. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6926. *
  6927. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6928. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6929. */
  6930. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6931. var num = Scalar.DeltaAngle(current, target);
  6932. var result = 0;
  6933. if (-maxDelta < num && num < maxDelta) {
  6934. result = target;
  6935. }
  6936. else {
  6937. target = current + num;
  6938. result = Scalar.MoveTowards(current, target, maxDelta);
  6939. }
  6940. return result;
  6941. };
  6942. /**
  6943. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6944. */
  6945. Scalar.Lerp = function (start, end, amount) {
  6946. return start + ((end - start) * amount);
  6947. };
  6948. /**
  6949. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6950. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6951. */
  6952. Scalar.LerpAngle = function (start, end, amount) {
  6953. var num = Scalar.Repeat(end - start, 360.0);
  6954. if (num > 180.0) {
  6955. num -= 360.0;
  6956. }
  6957. return start + num * Scalar.Clamp(amount);
  6958. };
  6959. /**
  6960. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6961. */
  6962. Scalar.InverseLerp = function (a, b, value) {
  6963. var result = 0;
  6964. if (a != b) {
  6965. result = Scalar.Clamp((value - a) / (b - a));
  6966. }
  6967. else {
  6968. result = 0.0;
  6969. }
  6970. return result;
  6971. };
  6972. /**
  6973. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6974. */
  6975. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6976. var squared = amount * amount;
  6977. var cubed = amount * squared;
  6978. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6979. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6980. var part3 = (cubed - (2.0 * squared)) + amount;
  6981. var part4 = cubed - squared;
  6982. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6983. };
  6984. /**
  6985. * Returns a random float number between and min and max values
  6986. */
  6987. Scalar.RandomRange = function (min, max) {
  6988. if (min === max)
  6989. return min;
  6990. return ((Math.random() * (max - min)) + min);
  6991. };
  6992. /**
  6993. * This function returns percentage of a number in a given range.
  6994. *
  6995. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6996. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6997. */
  6998. Scalar.RangeToPercent = function (number, min, max) {
  6999. return ((number - min) / (max - min));
  7000. };
  7001. /**
  7002. * This function returns number that corresponds to the percentage in a given range.
  7003. *
  7004. * PercentToRange(0.34,0,100) will return 34.
  7005. */
  7006. Scalar.PercentToRange = function (percent, min, max) {
  7007. return ((max - min) * percent + min);
  7008. };
  7009. /**
  7010. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7011. * @param angle The angle to normalize in radian.
  7012. * @return The converted angle.
  7013. */
  7014. Scalar.NormalizeRadians = function (angle) {
  7015. // More precise but slower version kept for reference.
  7016. // angle = angle % Tools.TwoPi;
  7017. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7018. //if (angle > Math.PI) {
  7019. // angle -= Tools.TwoPi;
  7020. //}
  7021. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7022. return angle;
  7023. };
  7024. /**
  7025. * Two pi constants convenient for computation.
  7026. */
  7027. Scalar.TwoPi = Math.PI * 2;
  7028. return Scalar;
  7029. }());
  7030. BABYLON.Scalar = Scalar;
  7031. })(BABYLON || (BABYLON = {}));
  7032. //# sourceMappingURL=babylon.math.scalar.js.map
  7033. "use strict";
  7034. //# sourceMappingURL=babylon.mixins.js.map
  7035. "use strict";
  7036. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7037. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7038. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7039. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7040. //# sourceMappingURL=babylon.webgl2.js.map
  7041. "use strict";
  7042. var BABYLON;
  7043. (function (BABYLON) {
  7044. var __decoratorInitialStore = {};
  7045. var __mergedStore = {};
  7046. var _copySource = function (creationFunction, source, instanciate) {
  7047. var destination = creationFunction();
  7048. // Tags
  7049. if (BABYLON.Tags) {
  7050. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7051. }
  7052. var classStore = getMergedStore(destination);
  7053. // Properties
  7054. for (var property in classStore) {
  7055. var propertyDescriptor = classStore[property];
  7056. var sourceProperty = source[property];
  7057. var propertyType = propertyDescriptor.type;
  7058. if (sourceProperty !== undefined && sourceProperty !== null) {
  7059. switch (propertyType) {
  7060. case 0: // Value
  7061. case 6:// Mesh reference
  7062. destination[property] = sourceProperty;
  7063. break;
  7064. case 1:// Texture
  7065. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7066. break;
  7067. case 2: // Color3
  7068. case 3: // FresnelParameters
  7069. case 4: // Vector2
  7070. case 5: // Vector3
  7071. case 7: // Color Curves
  7072. case 10:// Quaternion
  7073. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7074. break;
  7075. }
  7076. }
  7077. }
  7078. return destination;
  7079. };
  7080. function getDirectStore(target) {
  7081. var classKey = target.getClassName();
  7082. if (!__decoratorInitialStore[classKey]) {
  7083. __decoratorInitialStore[classKey] = {};
  7084. }
  7085. return __decoratorInitialStore[classKey];
  7086. }
  7087. /**
  7088. * Return the list of properties flagged as serializable
  7089. * @param target: host object
  7090. */
  7091. function getMergedStore(target) {
  7092. var classKey = target.getClassName();
  7093. if (__mergedStore[classKey]) {
  7094. return __mergedStore[classKey];
  7095. }
  7096. __mergedStore[classKey] = {};
  7097. var store = __mergedStore[classKey];
  7098. var currentTarget = target;
  7099. var currentKey = classKey;
  7100. while (currentKey) {
  7101. var initialStore = __decoratorInitialStore[currentKey];
  7102. for (var property in initialStore) {
  7103. store[property] = initialStore[property];
  7104. }
  7105. var parent_1 = void 0;
  7106. var done = false;
  7107. do {
  7108. parent_1 = Object.getPrototypeOf(currentTarget);
  7109. if (!parent_1.getClassName) {
  7110. done = true;
  7111. break;
  7112. }
  7113. if (parent_1.getClassName() !== currentKey) {
  7114. break;
  7115. }
  7116. currentTarget = parent_1;
  7117. } while (parent_1);
  7118. if (done) {
  7119. break;
  7120. }
  7121. currentKey = parent_1.getClassName();
  7122. currentTarget = parent_1;
  7123. }
  7124. return store;
  7125. }
  7126. function generateSerializableMember(type, sourceName) {
  7127. return function (target, propertyKey) {
  7128. var classStore = getDirectStore(target);
  7129. if (!classStore[propertyKey]) {
  7130. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7131. }
  7132. };
  7133. }
  7134. function generateExpandMember(setCallback, targetKey) {
  7135. if (targetKey === void 0) { targetKey = null; }
  7136. return function (target, propertyKey) {
  7137. var key = targetKey || ("_" + propertyKey);
  7138. Object.defineProperty(target, propertyKey, {
  7139. get: function () {
  7140. return this[key];
  7141. },
  7142. set: function (value) {
  7143. if (this[key] === value) {
  7144. return;
  7145. }
  7146. this[key] = value;
  7147. target[setCallback].apply(this);
  7148. },
  7149. enumerable: true,
  7150. configurable: true
  7151. });
  7152. };
  7153. }
  7154. function expandToProperty(callback, targetKey) {
  7155. if (targetKey === void 0) { targetKey = null; }
  7156. return generateExpandMember(callback, targetKey);
  7157. }
  7158. BABYLON.expandToProperty = expandToProperty;
  7159. function serialize(sourceName) {
  7160. return generateSerializableMember(0, sourceName); // value member
  7161. }
  7162. BABYLON.serialize = serialize;
  7163. function serializeAsTexture(sourceName) {
  7164. return generateSerializableMember(1, sourceName); // texture member
  7165. }
  7166. BABYLON.serializeAsTexture = serializeAsTexture;
  7167. function serializeAsColor3(sourceName) {
  7168. return generateSerializableMember(2, sourceName); // color3 member
  7169. }
  7170. BABYLON.serializeAsColor3 = serializeAsColor3;
  7171. function serializeAsFresnelParameters(sourceName) {
  7172. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7173. }
  7174. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7175. function serializeAsVector2(sourceName) {
  7176. return generateSerializableMember(4, sourceName); // vector2 member
  7177. }
  7178. BABYLON.serializeAsVector2 = serializeAsVector2;
  7179. function serializeAsVector3(sourceName) {
  7180. return generateSerializableMember(5, sourceName); // vector3 member
  7181. }
  7182. BABYLON.serializeAsVector3 = serializeAsVector3;
  7183. function serializeAsMeshReference(sourceName) {
  7184. return generateSerializableMember(6, sourceName); // mesh reference member
  7185. }
  7186. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7187. function serializeAsColorCurves(sourceName) {
  7188. return generateSerializableMember(7, sourceName); // color curves
  7189. }
  7190. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7191. function serializeAsColor4(sourceName) {
  7192. return generateSerializableMember(8, sourceName); // color 4
  7193. }
  7194. BABYLON.serializeAsColor4 = serializeAsColor4;
  7195. function serializeAsImageProcessingConfiguration(sourceName) {
  7196. return generateSerializableMember(9, sourceName); // image processing
  7197. }
  7198. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7199. function serializeAsQuaternion(sourceName) {
  7200. return generateSerializableMember(10, sourceName); // quaternion member
  7201. }
  7202. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7203. var SerializationHelper = /** @class */ (function () {
  7204. function SerializationHelper() {
  7205. }
  7206. SerializationHelper.Serialize = function (entity, serializationObject) {
  7207. if (!serializationObject) {
  7208. serializationObject = {};
  7209. }
  7210. // Tags
  7211. if (BABYLON.Tags) {
  7212. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7213. }
  7214. var serializedProperties = getMergedStore(entity);
  7215. // Properties
  7216. for (var property in serializedProperties) {
  7217. var propertyDescriptor = serializedProperties[property];
  7218. var targetPropertyName = propertyDescriptor.sourceName || property;
  7219. var propertyType = propertyDescriptor.type;
  7220. var sourceProperty = entity[property];
  7221. if (sourceProperty !== undefined && sourceProperty !== null) {
  7222. switch (propertyType) {
  7223. case 0:// Value
  7224. serializationObject[targetPropertyName] = sourceProperty;
  7225. break;
  7226. case 1:// Texture
  7227. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7228. break;
  7229. case 2:// Color3
  7230. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7231. break;
  7232. case 3:// FresnelParameters
  7233. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7234. break;
  7235. case 4:// Vector2
  7236. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7237. break;
  7238. case 5:// Vector3
  7239. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7240. break;
  7241. case 6:// Mesh reference
  7242. serializationObject[targetPropertyName] = sourceProperty.id;
  7243. break;
  7244. case 7:// Color Curves
  7245. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7246. break;
  7247. case 8:// Color 4
  7248. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7249. break;
  7250. case 9:// Image Processing
  7251. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7252. break;
  7253. }
  7254. }
  7255. }
  7256. return serializationObject;
  7257. };
  7258. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7259. if (rootUrl === void 0) { rootUrl = null; }
  7260. var destination = creationFunction();
  7261. if (!rootUrl) {
  7262. rootUrl = "";
  7263. }
  7264. // Tags
  7265. if (BABYLON.Tags) {
  7266. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7267. }
  7268. var classStore = getMergedStore(destination);
  7269. // Properties
  7270. for (var property in classStore) {
  7271. var propertyDescriptor = classStore[property];
  7272. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7273. var propertyType = propertyDescriptor.type;
  7274. if (sourceProperty !== undefined && sourceProperty !== null) {
  7275. var dest = destination;
  7276. switch (propertyType) {
  7277. case 0:// Value
  7278. dest[property] = sourceProperty;
  7279. break;
  7280. case 1:// Texture
  7281. if (scene) {
  7282. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7283. }
  7284. break;
  7285. case 2:// Color3
  7286. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7287. break;
  7288. case 3:// FresnelParameters
  7289. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7290. break;
  7291. case 4:// Vector2
  7292. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7293. break;
  7294. case 5:// Vector3
  7295. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7296. break;
  7297. case 6:// Mesh reference
  7298. if (scene) {
  7299. dest[property] = scene.getLastMeshByID(sourceProperty);
  7300. }
  7301. break;
  7302. case 7:// Color Curves
  7303. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7304. break;
  7305. case 8:// Color 4
  7306. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7307. break;
  7308. case 9:// Image Processing
  7309. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7310. break;
  7311. }
  7312. }
  7313. }
  7314. return destination;
  7315. };
  7316. SerializationHelper.Clone = function (creationFunction, source) {
  7317. return _copySource(creationFunction, source, false);
  7318. };
  7319. SerializationHelper.Instanciate = function (creationFunction, source) {
  7320. return _copySource(creationFunction, source, true);
  7321. };
  7322. return SerializationHelper;
  7323. }());
  7324. BABYLON.SerializationHelper = SerializationHelper;
  7325. })(BABYLON || (BABYLON = {}));
  7326. //# sourceMappingURL=babylon.decorators.js.map
  7327. "use strict";
  7328. var BABYLON;
  7329. (function (BABYLON) {
  7330. /**
  7331. * Wrapper class for promise with external resolve and reject.
  7332. */
  7333. var Deferred = /** @class */ (function () {
  7334. /**
  7335. * Constructor for this deferred object.
  7336. */
  7337. function Deferred() {
  7338. var _this = this;
  7339. this.promise = new Promise(function (resolve, reject) {
  7340. _this._resolve = resolve;
  7341. _this._reject = reject;
  7342. });
  7343. }
  7344. Object.defineProperty(Deferred.prototype, "resolve", {
  7345. /**
  7346. * The resolve method of the promise associated with this deferred object.
  7347. */
  7348. get: function () {
  7349. return this._resolve;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Deferred.prototype, "reject", {
  7355. /**
  7356. * The reject method of the promise associated with this deferred object.
  7357. */
  7358. get: function () {
  7359. return this._reject;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. return Deferred;
  7365. }());
  7366. BABYLON.Deferred = Deferred;
  7367. })(BABYLON || (BABYLON = {}));
  7368. //# sourceMappingURL=babylon.deferred.js.map
  7369. "use strict";
  7370. var BABYLON;
  7371. (function (BABYLON) {
  7372. /**
  7373. * A class serves as a medium between the observable and its observers
  7374. */
  7375. var EventState = /** @class */ (function () {
  7376. /**
  7377. * Create a new EventState
  7378. * @param mask defines the mask associated with this state
  7379. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7380. * @param target defines the original target of the state
  7381. * @param currentTarget defines the current target of the state
  7382. */
  7383. function EventState(mask, skipNextObservers, target, currentTarget) {
  7384. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7385. this.initalize(mask, skipNextObservers, target, currentTarget);
  7386. }
  7387. /**
  7388. * Initialize the current event state
  7389. * @param mask defines the mask associated with this state
  7390. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7391. * @param target defines the original target of the state
  7392. * @param currentTarget defines the current target of the state
  7393. * @returns the current event state
  7394. */
  7395. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7396. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7397. this.mask = mask;
  7398. this.skipNextObservers = skipNextObservers;
  7399. this.target = target;
  7400. this.currentTarget = currentTarget;
  7401. return this;
  7402. };
  7403. return EventState;
  7404. }());
  7405. BABYLON.EventState = EventState;
  7406. /**
  7407. * Represent an Observer registered to a given Observable object.
  7408. */
  7409. var Observer = /** @class */ (function () {
  7410. /**
  7411. * Creates a new observer
  7412. * @param callback defines the callback to call when the observer is notified
  7413. * @param mask defines the mask of the observer (used to filter notifications)
  7414. * @param scope defines the current scope used to restore the JS context
  7415. */
  7416. function Observer(
  7417. /**
  7418. * Defines the callback to call when the observer is notified
  7419. */
  7420. callback,
  7421. /**
  7422. * Defines the mask of the observer (used to filter notifications)
  7423. */
  7424. mask,
  7425. /**
  7426. * Defines the current scope used to restore the JS context
  7427. */
  7428. scope) {
  7429. if (scope === void 0) { scope = null; }
  7430. this.callback = callback;
  7431. this.mask = mask;
  7432. this.scope = scope;
  7433. /** @ignore */
  7434. this._willBeUnregistered = false;
  7435. /**
  7436. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7437. */
  7438. this.unregisterOnNextCall = false;
  7439. }
  7440. return Observer;
  7441. }());
  7442. BABYLON.Observer = Observer;
  7443. /**
  7444. * Represent a list of observers registered to multiple Observables object.
  7445. */
  7446. var MultiObserver = /** @class */ (function () {
  7447. function MultiObserver() {
  7448. }
  7449. /**
  7450. * Release associated resources
  7451. */
  7452. MultiObserver.prototype.dispose = function () {
  7453. if (this._observers && this._observables) {
  7454. for (var index = 0; index < this._observers.length; index++) {
  7455. this._observables[index].remove(this._observers[index]);
  7456. }
  7457. }
  7458. this._observers = null;
  7459. this._observables = null;
  7460. };
  7461. /**
  7462. * Raise a callback when one of the observable will notify
  7463. * @param observables defines a list of observables to watch
  7464. * @param callback defines the callback to call on notification
  7465. * @param mask defines the mask used to filter notifications
  7466. * @param scope defines the current scope used to restore the JS context
  7467. * @returns the new MultiObserver
  7468. */
  7469. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7470. if (mask === void 0) { mask = -1; }
  7471. if (scope === void 0) { scope = null; }
  7472. var result = new MultiObserver();
  7473. result._observers = new Array();
  7474. result._observables = observables;
  7475. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7476. var observable = observables_1[_i];
  7477. var observer = observable.add(callback, mask, false, scope);
  7478. if (observer) {
  7479. result._observers.push(observer);
  7480. }
  7481. }
  7482. return result;
  7483. };
  7484. return MultiObserver;
  7485. }());
  7486. BABYLON.MultiObserver = MultiObserver;
  7487. /**
  7488. * The Observable class is a simple implementation of the Observable pattern.
  7489. * 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.
  7490. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7491. * 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).
  7492. * 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.
  7493. */
  7494. var Observable = /** @class */ (function () {
  7495. /**
  7496. * Creates a new observable
  7497. * @param onObserverAdded defines a callback to call when a new observer is added
  7498. */
  7499. function Observable(onObserverAdded) {
  7500. this._observers = new Array();
  7501. this._eventState = new EventState(0);
  7502. if (onObserverAdded) {
  7503. this._onObserverAdded = onObserverAdded;
  7504. }
  7505. }
  7506. /**
  7507. * Create a new Observer with the specified callback
  7508. * @param callback the callback that will be executed for that Observer
  7509. * @param mask the mask used to filter observers
  7510. * @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.
  7511. * @param scope optional scope for the callback to be called from
  7512. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7513. * @returns the new observer created for the callback
  7514. */
  7515. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7516. if (mask === void 0) { mask = -1; }
  7517. if (insertFirst === void 0) { insertFirst = false; }
  7518. if (scope === void 0) { scope = null; }
  7519. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7520. if (!callback) {
  7521. return null;
  7522. }
  7523. var observer = new Observer(callback, mask, scope);
  7524. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7525. if (insertFirst) {
  7526. this._observers.unshift(observer);
  7527. }
  7528. else {
  7529. this._observers.push(observer);
  7530. }
  7531. if (this._onObserverAdded) {
  7532. this._onObserverAdded(observer);
  7533. }
  7534. return observer;
  7535. };
  7536. /**
  7537. * Remove an Observer from the Observable object
  7538. * @param observer the instance of the Observer to remove
  7539. * @returns false if it doesn't belong to this Observable
  7540. */
  7541. Observable.prototype.remove = function (observer) {
  7542. if (!observer) {
  7543. return false;
  7544. }
  7545. var index = this._observers.indexOf(observer);
  7546. if (index !== -1) {
  7547. this._observers.splice(index, 1);
  7548. return true;
  7549. }
  7550. return false;
  7551. };
  7552. /**
  7553. * Remove a callback from the Observable object
  7554. * @param callback the callback to remove
  7555. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7556. * @returns false if it doesn't belong to this Observable
  7557. */
  7558. Observable.prototype.removeCallback = function (callback, scope) {
  7559. for (var index = 0; index < this._observers.length; index++) {
  7560. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7561. this._observers.splice(index, 1);
  7562. return true;
  7563. }
  7564. }
  7565. return false;
  7566. };
  7567. Observable.prototype._deferUnregister = function (observer) {
  7568. var _this = this;
  7569. observer.unregisterOnNextCall = false;
  7570. observer._willBeUnregistered = true;
  7571. BABYLON.Tools.SetImmediate(function () {
  7572. _this.remove(observer);
  7573. });
  7574. };
  7575. /**
  7576. * Notify all Observers by calling their respective callback with the given data
  7577. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7578. * @param eventData defines the data to send to all observers
  7579. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7580. * @param target defines the original target of the state
  7581. * @param currentTarget defines the current target of the state
  7582. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7583. */
  7584. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7585. if (mask === void 0) { mask = -1; }
  7586. if (!this._observers.length) {
  7587. return true;
  7588. }
  7589. var state = this._eventState;
  7590. state.mask = mask;
  7591. state.target = target;
  7592. state.currentTarget = currentTarget;
  7593. state.skipNextObservers = false;
  7594. state.lastReturnValue = eventData;
  7595. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7596. var obs = _a[_i];
  7597. if (obs._willBeUnregistered) {
  7598. continue;
  7599. }
  7600. if (obs.mask & mask) {
  7601. if (obs.scope) {
  7602. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7603. }
  7604. else {
  7605. state.lastReturnValue = obs.callback(eventData, state);
  7606. }
  7607. if (obs.unregisterOnNextCall) {
  7608. this._deferUnregister(obs);
  7609. }
  7610. }
  7611. if (state.skipNextObservers) {
  7612. return false;
  7613. }
  7614. }
  7615. return true;
  7616. };
  7617. /**
  7618. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7619. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7620. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7621. * and it is crucial that all callbacks will be executed.
  7622. * The order of the callbacks is kept, callbacks are not executed parallel.
  7623. *
  7624. * @param eventData The data to be sent to each callback
  7625. * @param mask is used to filter observers defaults to -1
  7626. * @param target defines the callback target (see EventState)
  7627. * @param currentTarget defines he current object in the bubbling phase
  7628. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7629. */
  7630. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7631. var _this = this;
  7632. if (mask === void 0) { mask = -1; }
  7633. // create an empty promise
  7634. var p = Promise.resolve(eventData);
  7635. // no observers? return this promise.
  7636. if (!this._observers.length) {
  7637. return p;
  7638. }
  7639. var state = this._eventState;
  7640. state.mask = mask;
  7641. state.target = target;
  7642. state.currentTarget = currentTarget;
  7643. state.skipNextObservers = false;
  7644. // execute one callback after another (not using Promise.all, the order is important)
  7645. this._observers.forEach(function (obs) {
  7646. if (state.skipNextObservers) {
  7647. return;
  7648. }
  7649. if (obs._willBeUnregistered) {
  7650. return;
  7651. }
  7652. if (obs.mask & mask) {
  7653. if (obs.scope) {
  7654. p = p.then(function (lastReturnedValue) {
  7655. state.lastReturnValue = lastReturnedValue;
  7656. return obs.callback.apply(obs.scope, [eventData, state]);
  7657. });
  7658. }
  7659. else {
  7660. p = p.then(function (lastReturnedValue) {
  7661. state.lastReturnValue = lastReturnedValue;
  7662. return obs.callback(eventData, state);
  7663. });
  7664. }
  7665. if (obs.unregisterOnNextCall) {
  7666. _this._deferUnregister(obs);
  7667. }
  7668. }
  7669. });
  7670. // return the eventData
  7671. return p.then(function () { return eventData; });
  7672. };
  7673. /**
  7674. * Notify a specific observer
  7675. * @param observer defines the observer to notify
  7676. * @param eventData defines the data to be sent to each callback
  7677. * @param mask is used to filter observers defaults to -1
  7678. */
  7679. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7680. if (mask === void 0) { mask = -1; }
  7681. var state = this._eventState;
  7682. state.mask = mask;
  7683. state.skipNextObservers = false;
  7684. observer.callback(eventData, state);
  7685. };
  7686. /**
  7687. * Gets a boolean indicating if the observable has at least one observer
  7688. * @returns true is the Observable has at least one Observer registered
  7689. */
  7690. Observable.prototype.hasObservers = function () {
  7691. return this._observers.length > 0;
  7692. };
  7693. /**
  7694. * Clear the list of observers
  7695. */
  7696. Observable.prototype.clear = function () {
  7697. this._observers = new Array();
  7698. this._onObserverAdded = null;
  7699. };
  7700. /**
  7701. * Clone the current observable
  7702. * @returns a new observable
  7703. */
  7704. Observable.prototype.clone = function () {
  7705. var result = new Observable();
  7706. result._observers = this._observers.slice(0);
  7707. return result;
  7708. };
  7709. /**
  7710. * Does this observable handles observer registered with a given mask
  7711. * @param mask defines the mask to be tested
  7712. * @return whether or not one observer registered with the given mask is handeled
  7713. **/
  7714. Observable.prototype.hasSpecificMask = function (mask) {
  7715. if (mask === void 0) { mask = -1; }
  7716. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7717. var obs = _a[_i];
  7718. if (obs.mask & mask || obs.mask === mask) {
  7719. return true;
  7720. }
  7721. }
  7722. return false;
  7723. };
  7724. return Observable;
  7725. }());
  7726. BABYLON.Observable = Observable;
  7727. })(BABYLON || (BABYLON = {}));
  7728. //# sourceMappingURL=babylon.observable.js.map
  7729. "use strict";
  7730. var BABYLON;
  7731. (function (BABYLON) {
  7732. var SmartArray = /** @class */ (function () {
  7733. function SmartArray(capacity) {
  7734. this.length = 0;
  7735. this.data = new Array(capacity);
  7736. this._id = SmartArray._GlobalId++;
  7737. }
  7738. SmartArray.prototype.push = function (value) {
  7739. this.data[this.length++] = value;
  7740. if (this.length > this.data.length) {
  7741. this.data.length *= 2;
  7742. }
  7743. };
  7744. SmartArray.prototype.forEach = function (func) {
  7745. for (var index = 0; index < this.length; index++) {
  7746. func(this.data[index]);
  7747. }
  7748. };
  7749. SmartArray.prototype.sort = function (compareFn) {
  7750. this.data.sort(compareFn);
  7751. };
  7752. SmartArray.prototype.reset = function () {
  7753. this.length = 0;
  7754. };
  7755. SmartArray.prototype.dispose = function () {
  7756. this.reset();
  7757. if (this.data) {
  7758. this.data.length = 0;
  7759. this.data = [];
  7760. }
  7761. };
  7762. SmartArray.prototype.concat = function (array) {
  7763. if (array.length === 0) {
  7764. return;
  7765. }
  7766. if (this.length + array.length > this.data.length) {
  7767. this.data.length = (this.length + array.length) * 2;
  7768. }
  7769. for (var index = 0; index < array.length; index++) {
  7770. this.data[this.length++] = (array.data || array)[index];
  7771. }
  7772. };
  7773. SmartArray.prototype.indexOf = function (value) {
  7774. var position = this.data.indexOf(value);
  7775. if (position >= this.length) {
  7776. return -1;
  7777. }
  7778. return position;
  7779. };
  7780. SmartArray.prototype.contains = function (value) {
  7781. return this.data.indexOf(value) !== -1;
  7782. };
  7783. // Statics
  7784. SmartArray._GlobalId = 0;
  7785. return SmartArray;
  7786. }());
  7787. BABYLON.SmartArray = SmartArray;
  7788. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7789. __extends(SmartArrayNoDuplicate, _super);
  7790. function SmartArrayNoDuplicate() {
  7791. var _this = _super !== null && _super.apply(this, arguments) || this;
  7792. _this._duplicateId = 0;
  7793. return _this;
  7794. }
  7795. SmartArrayNoDuplicate.prototype.push = function (value) {
  7796. _super.prototype.push.call(this, value);
  7797. if (!value.__smartArrayFlags) {
  7798. value.__smartArrayFlags = {};
  7799. }
  7800. value.__smartArrayFlags[this._id] = this._duplicateId;
  7801. };
  7802. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7803. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7804. return false;
  7805. }
  7806. this.push(value);
  7807. return true;
  7808. };
  7809. SmartArrayNoDuplicate.prototype.reset = function () {
  7810. _super.prototype.reset.call(this);
  7811. this._duplicateId++;
  7812. };
  7813. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7814. if (array.length === 0) {
  7815. return;
  7816. }
  7817. if (this.length + array.length > this.data.length) {
  7818. this.data.length = (this.length + array.length) * 2;
  7819. }
  7820. for (var index = 0; index < array.length; index++) {
  7821. var item = (array.data || array)[index];
  7822. this.pushNoDuplicate(item);
  7823. }
  7824. };
  7825. return SmartArrayNoDuplicate;
  7826. }(SmartArray));
  7827. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7828. })(BABYLON || (BABYLON = {}));
  7829. //# sourceMappingURL=babylon.smartArray.js.map
  7830. "use strict";
  7831. var BABYLON;
  7832. (function (BABYLON) {
  7833. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7834. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7835. var LoadFileError = /** @class */ (function (_super) {
  7836. __extends(LoadFileError, _super);
  7837. function LoadFileError(message, request) {
  7838. var _this = _super.call(this, message) || this;
  7839. _this.request = request;
  7840. _this.name = "LoadFileError";
  7841. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7842. return _this;
  7843. }
  7844. // Polyfill for Object.setPrototypeOf if necessary.
  7845. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7846. return LoadFileError;
  7847. }(Error));
  7848. BABYLON.LoadFileError = LoadFileError;
  7849. var RetryStrategy = /** @class */ (function () {
  7850. function RetryStrategy() {
  7851. }
  7852. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7853. if (maxRetries === void 0) { maxRetries = 3; }
  7854. if (baseInterval === void 0) { baseInterval = 500; }
  7855. return function (url, request, retryIndex) {
  7856. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7857. return -1;
  7858. }
  7859. return Math.pow(2, retryIndex) * baseInterval;
  7860. };
  7861. };
  7862. return RetryStrategy;
  7863. }());
  7864. BABYLON.RetryStrategy = RetryStrategy;
  7865. // Screenshots
  7866. var screenshotCanvas;
  7867. var cloneValue = function (source, destinationObject) {
  7868. if (!source)
  7869. return null;
  7870. if (source instanceof BABYLON.Mesh) {
  7871. return null;
  7872. }
  7873. if (source instanceof BABYLON.SubMesh) {
  7874. return source.clone(destinationObject);
  7875. }
  7876. else if (source.clone) {
  7877. return source.clone();
  7878. }
  7879. return null;
  7880. };
  7881. var Tools = /** @class */ (function () {
  7882. function Tools() {
  7883. }
  7884. /**
  7885. * Interpolates between a and b via alpha
  7886. * @param a The lower value (returned when alpha = 0)
  7887. * @param b The upper value (returned when alpha = 1)
  7888. * @param alpha The interpolation-factor
  7889. * @return The mixed value
  7890. */
  7891. Tools.Mix = function (a, b, alpha) {
  7892. return a * (1 - alpha) + b * alpha;
  7893. };
  7894. Tools.Instantiate = function (className) {
  7895. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7896. return Tools.RegisteredExternalClasses[className];
  7897. }
  7898. var arr = className.split(".");
  7899. var fn = (window || this);
  7900. for (var i = 0, len = arr.length; i < len; i++) {
  7901. fn = fn[arr[i]];
  7902. }
  7903. if (typeof fn !== "function") {
  7904. return null;
  7905. }
  7906. return fn;
  7907. };
  7908. /**
  7909. * Provides a slice function that will work even on IE
  7910. * @param data defines the array to slice
  7911. * @returns the new sliced array
  7912. */
  7913. Tools.Slice = function (data) {
  7914. if (data.slice) {
  7915. return data.slice();
  7916. }
  7917. return Array.prototype.slice.call(data);
  7918. };
  7919. Tools.SetImmediate = function (action) {
  7920. if (window.setImmediate) {
  7921. window.setImmediate(action);
  7922. }
  7923. else {
  7924. setTimeout(action, 1);
  7925. }
  7926. };
  7927. Tools.IsExponentOfTwo = function (value) {
  7928. var count = 1;
  7929. do {
  7930. count *= 2;
  7931. } while (count < value);
  7932. return count === value;
  7933. };
  7934. /**
  7935. * Find the next highest power of two.
  7936. * @param x Number to start search from.
  7937. * @return Next highest power of two.
  7938. */
  7939. Tools.CeilingPOT = function (x) {
  7940. x--;
  7941. x |= x >> 1;
  7942. x |= x >> 2;
  7943. x |= x >> 4;
  7944. x |= x >> 8;
  7945. x |= x >> 16;
  7946. x++;
  7947. return x;
  7948. };
  7949. /**
  7950. * Find the next lowest power of two.
  7951. * @param x Number to start search from.
  7952. * @return Next lowest power of two.
  7953. */
  7954. Tools.FloorPOT = function (x) {
  7955. x = x | (x >> 1);
  7956. x = x | (x >> 2);
  7957. x = x | (x >> 4);
  7958. x = x | (x >> 8);
  7959. x = x | (x >> 16);
  7960. return x - (x >> 1);
  7961. };
  7962. /**
  7963. * Find the nearest power of two.
  7964. * @param x Number to start search from.
  7965. * @return Next nearest power of two.
  7966. */
  7967. Tools.NearestPOT = function (x) {
  7968. var c = Tools.CeilingPOT(x);
  7969. var f = Tools.FloorPOT(x);
  7970. return (c - x) > (x - f) ? f : c;
  7971. };
  7972. Tools.GetExponentOfTwo = function (value, max, mode) {
  7973. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7974. var pot;
  7975. switch (mode) {
  7976. case BABYLON.Engine.SCALEMODE_FLOOR:
  7977. pot = Tools.FloorPOT(value);
  7978. break;
  7979. case BABYLON.Engine.SCALEMODE_NEAREST:
  7980. pot = Tools.NearestPOT(value);
  7981. break;
  7982. case BABYLON.Engine.SCALEMODE_CEILING:
  7983. default:
  7984. pot = Tools.CeilingPOT(value);
  7985. break;
  7986. }
  7987. return Math.min(pot, max);
  7988. };
  7989. Tools.GetFilename = function (path) {
  7990. var index = path.lastIndexOf("/");
  7991. if (index < 0)
  7992. return path;
  7993. return path.substring(index + 1);
  7994. };
  7995. /**
  7996. * Extracts the "folder" part of a path (everything before the filename).
  7997. * @param uri The URI to extract the info from
  7998. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7999. * @returns The "folder" part of the path
  8000. */
  8001. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8002. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8003. var index = uri.lastIndexOf("/");
  8004. if (index < 0) {
  8005. if (returnUnchangedIfNoSlash) {
  8006. return uri;
  8007. }
  8008. return "";
  8009. }
  8010. return uri.substring(0, index + 1);
  8011. };
  8012. Tools.GetDOMTextContent = function (element) {
  8013. var result = "";
  8014. var child = element.firstChild;
  8015. while (child) {
  8016. if (child.nodeType === 3) {
  8017. result += child.textContent;
  8018. }
  8019. child = child.nextSibling;
  8020. }
  8021. return result;
  8022. };
  8023. Tools.ToDegrees = function (angle) {
  8024. return angle * 180 / Math.PI;
  8025. };
  8026. Tools.ToRadians = function (angle) {
  8027. return angle * Math.PI / 180;
  8028. };
  8029. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8030. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8031. var output = "";
  8032. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8033. var i = 0;
  8034. var bytes = new Uint8Array(buffer);
  8035. while (i < bytes.length) {
  8036. chr1 = bytes[i++];
  8037. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8038. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8039. enc1 = chr1 >> 2;
  8040. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8041. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8042. enc4 = chr3 & 63;
  8043. if (isNaN(chr2)) {
  8044. enc3 = enc4 = 64;
  8045. }
  8046. else if (isNaN(chr3)) {
  8047. enc4 = 64;
  8048. }
  8049. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8050. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8051. }
  8052. return "data:image/png;base64," + output;
  8053. };
  8054. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8055. if (bias === void 0) { bias = null; }
  8056. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8057. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8058. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8059. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8060. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8061. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8062. }
  8063. if (bias) {
  8064. minimum.x -= minimum.x * bias.x + bias.y;
  8065. minimum.y -= minimum.y * bias.x + bias.y;
  8066. minimum.z -= minimum.z * bias.x + bias.y;
  8067. maximum.x += maximum.x * bias.x + bias.y;
  8068. maximum.y += maximum.y * bias.x + bias.y;
  8069. maximum.z += maximum.z * bias.x + bias.y;
  8070. }
  8071. return {
  8072. minimum: minimum,
  8073. maximum: maximum
  8074. };
  8075. };
  8076. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8077. if (bias === void 0) { bias = null; }
  8078. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8079. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8080. if (!stride) {
  8081. stride = 3;
  8082. }
  8083. for (var index = start; index < start + count; index++) {
  8084. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8085. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8086. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8087. }
  8088. if (bias) {
  8089. minimum.x -= minimum.x * bias.x + bias.y;
  8090. minimum.y -= minimum.y * bias.x + bias.y;
  8091. minimum.z -= minimum.z * bias.x + bias.y;
  8092. maximum.x += maximum.x * bias.x + bias.y;
  8093. maximum.y += maximum.y * bias.x + bias.y;
  8094. maximum.z += maximum.z * bias.x + bias.y;
  8095. }
  8096. return {
  8097. minimum: minimum,
  8098. maximum: maximum
  8099. };
  8100. };
  8101. Tools.Vector2ArrayFeeder = function (array) {
  8102. return function (index) {
  8103. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8104. var length = isFloatArray ? array.length / 2 : array.length;
  8105. if (index >= length) {
  8106. return null;
  8107. }
  8108. if (isFloatArray) {
  8109. var fa = array;
  8110. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8111. }
  8112. var a = array;
  8113. return a[index];
  8114. };
  8115. };
  8116. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8117. if (bias === void 0) { bias = null; }
  8118. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8119. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8120. var i = 0;
  8121. var cur = feeder(i++);
  8122. while (cur) {
  8123. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8124. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8125. cur = feeder(i++);
  8126. }
  8127. if (bias) {
  8128. minimum.x -= minimum.x * bias.x + bias.y;
  8129. minimum.y -= minimum.y * bias.x + bias.y;
  8130. maximum.x += maximum.x * bias.x + bias.y;
  8131. maximum.y += maximum.y * bias.x + bias.y;
  8132. }
  8133. return {
  8134. minimum: minimum,
  8135. maximum: maximum
  8136. };
  8137. };
  8138. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8139. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8140. return null;
  8141. return Array.isArray(obj) ? obj : [obj];
  8142. };
  8143. // Misc.
  8144. Tools.GetPointerPrefix = function () {
  8145. var eventPrefix = "pointer";
  8146. // Check if pointer events are supported
  8147. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8148. eventPrefix = "mouse";
  8149. }
  8150. return eventPrefix;
  8151. };
  8152. /**
  8153. * @param func - the function to be called
  8154. * @param requester - the object that will request the next frame. Falls back to window.
  8155. */
  8156. Tools.QueueNewFrame = function (func, requester) {
  8157. if (!Tools.IsWindowObjectExist()) {
  8158. return setTimeout(func, 16);
  8159. }
  8160. if (!requester) {
  8161. requester = window;
  8162. }
  8163. if (requester.requestAnimationFrame) {
  8164. return requester.requestAnimationFrame(func);
  8165. }
  8166. else if (requester.msRequestAnimationFrame) {
  8167. return requester.msRequestAnimationFrame(func);
  8168. }
  8169. else if (requester.webkitRequestAnimationFrame) {
  8170. return requester.webkitRequestAnimationFrame(func);
  8171. }
  8172. else if (requester.mozRequestAnimationFrame) {
  8173. return requester.mozRequestAnimationFrame(func);
  8174. }
  8175. else if (requester.oRequestAnimationFrame) {
  8176. return requester.oRequestAnimationFrame(func);
  8177. }
  8178. else {
  8179. return window.setTimeout(func, 16);
  8180. }
  8181. };
  8182. Tools.RequestFullscreen = function (element) {
  8183. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8184. if (!requestFunction)
  8185. return;
  8186. requestFunction.call(element);
  8187. };
  8188. Tools.ExitFullscreen = function () {
  8189. if (document.exitFullscreen) {
  8190. document.exitFullscreen();
  8191. }
  8192. else if (document.mozCancelFullScreen) {
  8193. document.mozCancelFullScreen();
  8194. }
  8195. else if (document.webkitCancelFullScreen) {
  8196. document.webkitCancelFullScreen();
  8197. }
  8198. else if (document.msCancelFullScreen) {
  8199. document.msCancelFullScreen();
  8200. }
  8201. };
  8202. Tools.SetCorsBehavior = function (url, element) {
  8203. if (url && url.indexOf("data:") === 0) {
  8204. return;
  8205. }
  8206. if (Tools.CorsBehavior) {
  8207. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8208. element.crossOrigin = Tools.CorsBehavior;
  8209. }
  8210. else {
  8211. var result = Tools.CorsBehavior(url);
  8212. if (result) {
  8213. element.crossOrigin = result;
  8214. }
  8215. }
  8216. }
  8217. };
  8218. // External files
  8219. Tools.CleanUrl = function (url) {
  8220. url = url.replace(/#/mg, "%23");
  8221. return url;
  8222. };
  8223. Tools.LoadImage = function (url, onLoad, onError, database) {
  8224. if (url instanceof ArrayBuffer) {
  8225. url = Tools.EncodeArrayBufferTobase64(url);
  8226. }
  8227. url = Tools.CleanUrl(url);
  8228. url = Tools.PreprocessUrl(url);
  8229. var img = new Image();
  8230. Tools.SetCorsBehavior(url, img);
  8231. var loadHandler = function () {
  8232. img.removeEventListener("load", loadHandler);
  8233. img.removeEventListener("error", errorHandler);
  8234. onLoad(img);
  8235. };
  8236. var errorHandler = function (err) {
  8237. img.removeEventListener("load", loadHandler);
  8238. img.removeEventListener("error", errorHandler);
  8239. Tools.Error("Error while trying to load image: " + url);
  8240. if (onError) {
  8241. onError("Error while trying to load image: " + url, err);
  8242. }
  8243. };
  8244. img.addEventListener("load", loadHandler);
  8245. img.addEventListener("error", errorHandler);
  8246. var noIndexedDB = function () {
  8247. img.src = url;
  8248. };
  8249. var loadFromIndexedDB = function () {
  8250. if (database) {
  8251. database.loadImageFromDB(url, img);
  8252. }
  8253. };
  8254. //ANY database to do!
  8255. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8256. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8257. }
  8258. else {
  8259. if (url.indexOf("file:") !== -1) {
  8260. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8261. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8262. try {
  8263. var blobURL;
  8264. try {
  8265. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8266. }
  8267. catch (ex) {
  8268. // Chrome doesn't support oneTimeOnly parameter
  8269. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8270. }
  8271. img.src = blobURL;
  8272. }
  8273. catch (e) {
  8274. img.src = "";
  8275. }
  8276. return img;
  8277. }
  8278. }
  8279. noIndexedDB();
  8280. }
  8281. return img;
  8282. };
  8283. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8284. url = Tools.CleanUrl(url);
  8285. url = Tools.PreprocessUrl(url);
  8286. // If file and file input are set
  8287. if (url.indexOf("file:") !== -1) {
  8288. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8289. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8290. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8291. }
  8292. }
  8293. var loadUrl = Tools.BaseUrl + url;
  8294. var aborted = false;
  8295. var fileRequest = {
  8296. onCompleteObservable: new BABYLON.Observable(),
  8297. abort: function () { return aborted = true; },
  8298. };
  8299. var requestFile = function () {
  8300. var request = new XMLHttpRequest();
  8301. var retryHandle = null;
  8302. fileRequest.abort = function () {
  8303. aborted = true;
  8304. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8305. request.abort();
  8306. }
  8307. if (retryHandle !== null) {
  8308. clearTimeout(retryHandle);
  8309. retryHandle = null;
  8310. }
  8311. };
  8312. var retryLoop = function (retryIndex) {
  8313. request.open('GET', loadUrl, true);
  8314. if (useArrayBuffer) {
  8315. request.responseType = "arraybuffer";
  8316. }
  8317. if (onProgress) {
  8318. request.addEventListener("progress", onProgress);
  8319. }
  8320. var onLoadEnd = function () {
  8321. request.removeEventListener("loadend", onLoadEnd);
  8322. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8323. fileRequest.onCompleteObservable.clear();
  8324. };
  8325. request.addEventListener("loadend", onLoadEnd);
  8326. var onReadyStateChange = function () {
  8327. if (aborted) {
  8328. return;
  8329. }
  8330. // In case of undefined state in some browsers.
  8331. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8332. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8333. request.removeEventListener("readystatechange", onReadyStateChange);
  8334. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8335. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8336. return;
  8337. }
  8338. var retryStrategy = Tools.DefaultRetryStrategy;
  8339. if (retryStrategy) {
  8340. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8341. if (waitTime !== -1) {
  8342. // Prevent the request from completing for retry.
  8343. request.removeEventListener("loadend", onLoadEnd);
  8344. request = new XMLHttpRequest();
  8345. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8346. return;
  8347. }
  8348. }
  8349. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8350. if (onError) {
  8351. onError(request, e);
  8352. }
  8353. else {
  8354. throw e;
  8355. }
  8356. }
  8357. };
  8358. request.addEventListener("readystatechange", onReadyStateChange);
  8359. request.send();
  8360. };
  8361. retryLoop(0);
  8362. };
  8363. // Caching all files
  8364. if (database && database.enableSceneOffline) {
  8365. var noIndexedDB_1 = function () {
  8366. if (!aborted) {
  8367. requestFile();
  8368. }
  8369. };
  8370. var loadFromIndexedDB = function () {
  8371. // TODO: database needs to support aborting and should return a IFileRequest
  8372. if (aborted) {
  8373. return;
  8374. }
  8375. if (database) {
  8376. database.loadFileFromDB(url, function (data) {
  8377. if (!aborted) {
  8378. onSuccess(data);
  8379. }
  8380. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8381. }, onProgress ? function (event) {
  8382. if (!aborted) {
  8383. onProgress(event);
  8384. }
  8385. } : undefined, noIndexedDB_1, useArrayBuffer);
  8386. }
  8387. };
  8388. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8389. }
  8390. else {
  8391. requestFile();
  8392. }
  8393. return fileRequest;
  8394. };
  8395. /**
  8396. * Load a script (identified by an url). When the url returns, the
  8397. * content of this file is added into a new script element, attached to the DOM (body element)
  8398. */
  8399. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8400. var head = document.getElementsByTagName('head')[0];
  8401. var script = document.createElement('script');
  8402. script.type = 'text/javascript';
  8403. script.src = scriptUrl;
  8404. script.onload = function () {
  8405. if (onSuccess) {
  8406. onSuccess();
  8407. }
  8408. };
  8409. script.onerror = function (e) {
  8410. if (onError) {
  8411. onError("Unable to load script", e);
  8412. }
  8413. };
  8414. head.appendChild(script);
  8415. };
  8416. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8417. var reader = new FileReader();
  8418. var request = {
  8419. onCompleteObservable: new BABYLON.Observable(),
  8420. abort: function () { return reader.abort(); },
  8421. };
  8422. reader.onloadend = function (e) {
  8423. request.onCompleteObservable.notifyObservers(request);
  8424. };
  8425. reader.onload = function (e) {
  8426. //target doesn't have result from ts 1.3
  8427. callback(e.target['result']);
  8428. };
  8429. reader.onprogress = progressCallback;
  8430. reader.readAsDataURL(fileToLoad);
  8431. return request;
  8432. };
  8433. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8434. var reader = new FileReader();
  8435. var request = {
  8436. onCompleteObservable: new BABYLON.Observable(),
  8437. abort: function () { return reader.abort(); },
  8438. };
  8439. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8440. reader.onerror = function (e) {
  8441. Tools.Log("Error while reading file: " + fileToLoad.name);
  8442. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8443. };
  8444. reader.onload = function (e) {
  8445. //target doesn't have result from ts 1.3
  8446. callback(e.target['result']);
  8447. };
  8448. if (progressCallBack) {
  8449. reader.onprogress = progressCallBack;
  8450. }
  8451. if (!useArrayBuffer) {
  8452. // Asynchronous read
  8453. reader.readAsText(fileToLoad);
  8454. }
  8455. else {
  8456. reader.readAsArrayBuffer(fileToLoad);
  8457. }
  8458. return request;
  8459. };
  8460. //returns a downloadable url to a file content.
  8461. Tools.FileAsURL = function (content) {
  8462. var fileBlob = new Blob([content]);
  8463. var url = window.URL || window.webkitURL;
  8464. var link = url.createObjectURL(fileBlob);
  8465. return link;
  8466. };
  8467. // Misc.
  8468. Tools.Format = function (value, decimals) {
  8469. if (decimals === void 0) { decimals = 2; }
  8470. return value.toFixed(decimals);
  8471. };
  8472. Tools.CheckExtends = function (v, min, max) {
  8473. if (v.x < min.x)
  8474. min.x = v.x;
  8475. if (v.y < min.y)
  8476. min.y = v.y;
  8477. if (v.z < min.z)
  8478. min.z = v.z;
  8479. if (v.x > max.x)
  8480. max.x = v.x;
  8481. if (v.y > max.y)
  8482. max.y = v.y;
  8483. if (v.z > max.z)
  8484. max.z = v.z;
  8485. };
  8486. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8487. for (var prop in source) {
  8488. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8489. continue;
  8490. }
  8491. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8492. continue;
  8493. }
  8494. var sourceValue = source[prop];
  8495. var typeOfSourceValue = typeof sourceValue;
  8496. if (typeOfSourceValue === "function") {
  8497. continue;
  8498. }
  8499. try {
  8500. if (typeOfSourceValue === "object") {
  8501. if (sourceValue instanceof Array) {
  8502. destination[prop] = [];
  8503. if (sourceValue.length > 0) {
  8504. if (typeof sourceValue[0] == "object") {
  8505. for (var index = 0; index < sourceValue.length; index++) {
  8506. var clonedValue = cloneValue(sourceValue[index], destination);
  8507. if (destination[prop].indexOf(clonedValue) === -1) {
  8508. destination[prop].push(clonedValue);
  8509. }
  8510. }
  8511. }
  8512. else {
  8513. destination[prop] = sourceValue.slice(0);
  8514. }
  8515. }
  8516. }
  8517. else {
  8518. destination[prop] = cloneValue(sourceValue, destination);
  8519. }
  8520. }
  8521. else {
  8522. destination[prop] = sourceValue;
  8523. }
  8524. }
  8525. catch (e) {
  8526. // Just ignore error (it could be because of a read-only property)
  8527. }
  8528. }
  8529. };
  8530. Tools.IsEmpty = function (obj) {
  8531. for (var i in obj) {
  8532. if (obj.hasOwnProperty(i)) {
  8533. return false;
  8534. }
  8535. }
  8536. return true;
  8537. };
  8538. Tools.RegisterTopRootEvents = function (events) {
  8539. for (var index = 0; index < events.length; index++) {
  8540. var event = events[index];
  8541. window.addEventListener(event.name, event.handler, false);
  8542. try {
  8543. if (window.parent) {
  8544. window.parent.addEventListener(event.name, event.handler, false);
  8545. }
  8546. }
  8547. catch (e) {
  8548. // Silently fails...
  8549. }
  8550. }
  8551. };
  8552. Tools.UnregisterTopRootEvents = function (events) {
  8553. for (var index = 0; index < events.length; index++) {
  8554. var event = events[index];
  8555. window.removeEventListener(event.name, event.handler);
  8556. try {
  8557. if (window.parent) {
  8558. window.parent.removeEventListener(event.name, event.handler);
  8559. }
  8560. }
  8561. catch (e) {
  8562. // Silently fails...
  8563. }
  8564. }
  8565. };
  8566. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8567. if (mimeType === void 0) { mimeType = "image/png"; }
  8568. // Read the contents of the framebuffer
  8569. var numberOfChannelsByLine = width * 4;
  8570. var halfHeight = height / 2;
  8571. //Reading datas from WebGL
  8572. var data = engine.readPixels(0, 0, width, height);
  8573. //To flip image on Y axis.
  8574. for (var i = 0; i < halfHeight; i++) {
  8575. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8576. var currentCell = j + i * numberOfChannelsByLine;
  8577. var targetLine = height - i - 1;
  8578. var targetCell = j + targetLine * numberOfChannelsByLine;
  8579. var temp = data[currentCell];
  8580. data[currentCell] = data[targetCell];
  8581. data[targetCell] = temp;
  8582. }
  8583. }
  8584. // Create a 2D canvas to store the result
  8585. if (!screenshotCanvas) {
  8586. screenshotCanvas = document.createElement('canvas');
  8587. }
  8588. screenshotCanvas.width = width;
  8589. screenshotCanvas.height = height;
  8590. var context = screenshotCanvas.getContext('2d');
  8591. if (context) {
  8592. // Copy the pixels to a 2D canvas
  8593. var imageData = context.createImageData(width, height);
  8594. var castData = (imageData.data);
  8595. castData.set(data);
  8596. context.putImageData(imageData, 0, 0);
  8597. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8598. }
  8599. };
  8600. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8601. if (mimeType === void 0) { mimeType = "image/png"; }
  8602. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8603. if (successCallback) {
  8604. successCallback(base64Image);
  8605. }
  8606. else {
  8607. // We need HTMLCanvasElement.toBlob for HD screenshots
  8608. if (!screenshotCanvas.toBlob) {
  8609. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8610. screenshotCanvas.toBlob = function (callback, type, quality) {
  8611. var _this = this;
  8612. setTimeout(function () {
  8613. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8614. for (var i = 0; i < len; i++) {
  8615. arr[i] = binStr.charCodeAt(i);
  8616. }
  8617. callback(new Blob([arr], { type: type || 'image/png' }));
  8618. });
  8619. };
  8620. }
  8621. screenshotCanvas.toBlob(function (blob) {
  8622. var url = URL.createObjectURL(blob);
  8623. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8624. if (("download" in document.createElement("a"))) {
  8625. var a = window.document.createElement("a");
  8626. a.href = url;
  8627. if (fileName) {
  8628. a.setAttribute("download", fileName);
  8629. }
  8630. else {
  8631. var date = new Date();
  8632. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8633. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8634. }
  8635. window.document.body.appendChild(a);
  8636. a.addEventListener("click", function () {
  8637. if (a.parentElement) {
  8638. a.parentElement.removeChild(a);
  8639. }
  8640. });
  8641. a.click();
  8642. }
  8643. else {
  8644. var newWindow = window.open("");
  8645. if (!newWindow)
  8646. return;
  8647. var img = newWindow.document.createElement("img");
  8648. img.onload = function () {
  8649. // no longer need to read the blob so it's revoked
  8650. URL.revokeObjectURL(url);
  8651. };
  8652. img.src = url;
  8653. newWindow.document.body.appendChild(img);
  8654. }
  8655. });
  8656. }
  8657. };
  8658. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8659. if (mimeType === void 0) { mimeType = "image/png"; }
  8660. var width;
  8661. var height;
  8662. // If a precision value is specified
  8663. if (size.precision) {
  8664. width = Math.round(engine.getRenderWidth() * size.precision);
  8665. height = Math.round(width / engine.getAspectRatio(camera));
  8666. }
  8667. else if (size.width && size.height) {
  8668. width = size.width;
  8669. height = size.height;
  8670. }
  8671. else if (size.width && !size.height) {
  8672. width = size.width;
  8673. height = Math.round(width / engine.getAspectRatio(camera));
  8674. }
  8675. else if (size.height && !size.width) {
  8676. height = size.height;
  8677. width = Math.round(height * engine.getAspectRatio(camera));
  8678. }
  8679. else if (!isNaN(size)) {
  8680. height = size;
  8681. width = size;
  8682. }
  8683. else {
  8684. Tools.Error("Invalid 'size' parameter !");
  8685. return;
  8686. }
  8687. if (!screenshotCanvas) {
  8688. screenshotCanvas = document.createElement('canvas');
  8689. }
  8690. screenshotCanvas.width = width;
  8691. screenshotCanvas.height = height;
  8692. var renderContext = screenshotCanvas.getContext("2d");
  8693. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8694. var newWidth = width;
  8695. var newHeight = newWidth / ratio;
  8696. if (newHeight > height) {
  8697. newHeight = height;
  8698. newWidth = newHeight * ratio;
  8699. }
  8700. var offsetX = Math.max(0, width - newWidth) / 2;
  8701. var offsetY = Math.max(0, height - newHeight) / 2;
  8702. var renderingCanvas = engine.getRenderingCanvas();
  8703. if (renderContext && renderingCanvas) {
  8704. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8705. }
  8706. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8707. };
  8708. /**
  8709. * Generates an image screenshot from the specified camera.
  8710. *
  8711. * @param engine The engine to use for rendering
  8712. * @param camera The camera to use for rendering
  8713. * @param size This parameter can be set to a single number or to an object with the
  8714. * following (optional) properties: precision, width, height. If a single number is passed,
  8715. * it will be used for both width and height. If an object is passed, the screenshot size
  8716. * will be derived from the parameters. The precision property is a multiplier allowing
  8717. * rendering at a higher or lower resolution.
  8718. * @param successCallback The callback receives a single parameter which contains the
  8719. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8720. * src parameter of an <img> to display it.
  8721. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8722. * Check your browser for supported MIME types.
  8723. * @param samples Texture samples (default: 1)
  8724. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8725. * @param fileName A name for for the downloaded file.
  8726. * @constructor
  8727. */
  8728. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8729. if (mimeType === void 0) { mimeType = "image/png"; }
  8730. if (samples === void 0) { samples = 1; }
  8731. if (antialiasing === void 0) { antialiasing = false; }
  8732. var width;
  8733. var height;
  8734. //If a precision value is specified
  8735. if (size.precision) {
  8736. width = Math.round(engine.getRenderWidth() * size.precision);
  8737. height = Math.round(width / engine.getAspectRatio(camera));
  8738. size = { width: width, height: height };
  8739. }
  8740. else if (size.width && size.height) {
  8741. width = size.width;
  8742. height = size.height;
  8743. }
  8744. else if (size.width && !size.height) {
  8745. width = size.width;
  8746. height = Math.round(width / engine.getAspectRatio(camera));
  8747. size = { width: width, height: height };
  8748. }
  8749. else if (size.height && !size.width) {
  8750. height = size.height;
  8751. width = Math.round(height * engine.getAspectRatio(camera));
  8752. size = { width: width, height: height };
  8753. }
  8754. else if (!isNaN(size)) {
  8755. height = size;
  8756. width = size;
  8757. }
  8758. else {
  8759. Tools.Error("Invalid 'size' parameter !");
  8760. return;
  8761. }
  8762. var scene = camera.getScene();
  8763. var previousCamera = null;
  8764. if (scene.activeCamera !== camera) {
  8765. previousCamera = scene.activeCamera;
  8766. scene.activeCamera = camera;
  8767. }
  8768. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8769. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8770. texture.renderList = null;
  8771. texture.samples = samples;
  8772. if (antialiasing) {
  8773. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8774. }
  8775. texture.onAfterRenderObservable.add(function () {
  8776. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8777. });
  8778. scene.incrementRenderId();
  8779. scene.resetCachedMaterial();
  8780. texture.render(true);
  8781. texture.dispose();
  8782. if (previousCamera) {
  8783. scene.activeCamera = previousCamera;
  8784. }
  8785. camera.getProjectionMatrix(true); // Force cache refresh;
  8786. };
  8787. // XHR response validator for local file scenario
  8788. Tools.ValidateXHRData = function (xhr, dataType) {
  8789. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8790. if (dataType === void 0) { dataType = 7; }
  8791. try {
  8792. if (dataType & 1) {
  8793. if (xhr.responseText && xhr.responseText.length > 0) {
  8794. return true;
  8795. }
  8796. else if (dataType === 1) {
  8797. return false;
  8798. }
  8799. }
  8800. if (dataType & 2) {
  8801. // Check header width and height since there is no "TGA" magic number
  8802. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8803. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8804. return true;
  8805. }
  8806. else if (dataType === 2) {
  8807. return false;
  8808. }
  8809. }
  8810. if (dataType & 4) {
  8811. // Check for the "DDS" magic number
  8812. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8813. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8814. return true;
  8815. }
  8816. else {
  8817. return false;
  8818. }
  8819. }
  8820. }
  8821. catch (e) {
  8822. // Global protection
  8823. }
  8824. return false;
  8825. };
  8826. /**
  8827. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8828. * Be aware Math.random() could cause collisions, but:
  8829. * "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"
  8830. */
  8831. Tools.RandomId = function () {
  8832. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8833. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8834. return v.toString(16);
  8835. });
  8836. };
  8837. /**
  8838. * Test if the given uri is a base64 string.
  8839. * @param uri The uri to test
  8840. * @return True if the uri is a base64 string or false otherwise.
  8841. */
  8842. Tools.IsBase64 = function (uri) {
  8843. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8844. };
  8845. /**
  8846. * Decode the given base64 uri.
  8847. * @param uri The uri to decode
  8848. * @return The decoded base64 data.
  8849. */
  8850. Tools.DecodeBase64 = function (uri) {
  8851. var decodedString = atob(uri.split(",")[1]);
  8852. var bufferLength = decodedString.length;
  8853. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8854. for (var i = 0; i < bufferLength; i++) {
  8855. bufferView[i] = decodedString.charCodeAt(i);
  8856. }
  8857. return bufferView.buffer;
  8858. };
  8859. Object.defineProperty(Tools, "NoneLogLevel", {
  8860. get: function () {
  8861. return Tools._NoneLogLevel;
  8862. },
  8863. enumerable: true,
  8864. configurable: true
  8865. });
  8866. Object.defineProperty(Tools, "MessageLogLevel", {
  8867. get: function () {
  8868. return Tools._MessageLogLevel;
  8869. },
  8870. enumerable: true,
  8871. configurable: true
  8872. });
  8873. Object.defineProperty(Tools, "WarningLogLevel", {
  8874. get: function () {
  8875. return Tools._WarningLogLevel;
  8876. },
  8877. enumerable: true,
  8878. configurable: true
  8879. });
  8880. Object.defineProperty(Tools, "ErrorLogLevel", {
  8881. get: function () {
  8882. return Tools._ErrorLogLevel;
  8883. },
  8884. enumerable: true,
  8885. configurable: true
  8886. });
  8887. Object.defineProperty(Tools, "AllLogLevel", {
  8888. get: function () {
  8889. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8890. },
  8891. enumerable: true,
  8892. configurable: true
  8893. });
  8894. Tools._AddLogEntry = function (entry) {
  8895. Tools._LogCache = entry + Tools._LogCache;
  8896. if (Tools.OnNewCacheEntry) {
  8897. Tools.OnNewCacheEntry(entry);
  8898. }
  8899. };
  8900. Tools._FormatMessage = function (message) {
  8901. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8902. var date = new Date();
  8903. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8904. };
  8905. Tools._LogDisabled = function (message) {
  8906. // nothing to do
  8907. };
  8908. Tools._LogEnabled = function (message) {
  8909. var formattedMessage = Tools._FormatMessage(message);
  8910. console.log("BJS - " + formattedMessage);
  8911. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8912. Tools._AddLogEntry(entry);
  8913. };
  8914. Tools._WarnDisabled = function (message) {
  8915. // nothing to do
  8916. };
  8917. Tools._WarnEnabled = function (message) {
  8918. var formattedMessage = Tools._FormatMessage(message);
  8919. console.warn("BJS - " + formattedMessage);
  8920. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8921. Tools._AddLogEntry(entry);
  8922. };
  8923. Tools._ErrorDisabled = function (message) {
  8924. // nothing to do
  8925. };
  8926. Tools._ErrorEnabled = function (message) {
  8927. Tools.errorsCount++;
  8928. var formattedMessage = Tools._FormatMessage(message);
  8929. console.error("BJS - " + formattedMessage);
  8930. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8931. Tools._AddLogEntry(entry);
  8932. };
  8933. Object.defineProperty(Tools, "LogCache", {
  8934. get: function () {
  8935. return Tools._LogCache;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Tools.ClearLogCache = function () {
  8941. Tools._LogCache = "";
  8942. Tools.errorsCount = 0;
  8943. };
  8944. Object.defineProperty(Tools, "LogLevels", {
  8945. set: function (level) {
  8946. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8947. Tools.Log = Tools._LogEnabled;
  8948. }
  8949. else {
  8950. Tools.Log = Tools._LogDisabled;
  8951. }
  8952. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8953. Tools.Warn = Tools._WarnEnabled;
  8954. }
  8955. else {
  8956. Tools.Warn = Tools._WarnDisabled;
  8957. }
  8958. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8959. Tools.Error = Tools._ErrorEnabled;
  8960. }
  8961. else {
  8962. Tools.Error = Tools._ErrorDisabled;
  8963. }
  8964. },
  8965. enumerable: true,
  8966. configurable: true
  8967. });
  8968. Tools.IsWindowObjectExist = function () {
  8969. return (typeof window) !== "undefined";
  8970. };
  8971. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8972. get: function () {
  8973. return Tools._PerformanceNoneLogLevel;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8979. get: function () {
  8980. return Tools._PerformanceUserMarkLogLevel;
  8981. },
  8982. enumerable: true,
  8983. configurable: true
  8984. });
  8985. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8986. get: function () {
  8987. return Tools._PerformanceConsoleLogLevel;
  8988. },
  8989. enumerable: true,
  8990. configurable: true
  8991. });
  8992. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8993. set: function (level) {
  8994. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8995. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8996. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8997. return;
  8998. }
  8999. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9000. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9001. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9002. return;
  9003. }
  9004. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9005. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9006. },
  9007. enumerable: true,
  9008. configurable: true
  9009. });
  9010. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9011. };
  9012. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9013. };
  9014. Tools._StartUserMark = function (counterName, condition) {
  9015. if (condition === void 0) { condition = true; }
  9016. if (!Tools._performance) {
  9017. if (!Tools.IsWindowObjectExist()) {
  9018. return;
  9019. }
  9020. Tools._performance = window.performance;
  9021. }
  9022. if (!condition || !Tools._performance.mark) {
  9023. return;
  9024. }
  9025. Tools._performance.mark(counterName + "-Begin");
  9026. };
  9027. Tools._EndUserMark = function (counterName, condition) {
  9028. if (condition === void 0) { condition = true; }
  9029. if (!condition || !Tools._performance.mark) {
  9030. return;
  9031. }
  9032. Tools._performance.mark(counterName + "-End");
  9033. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9034. };
  9035. Tools._StartPerformanceConsole = function (counterName, condition) {
  9036. if (condition === void 0) { condition = true; }
  9037. if (!condition) {
  9038. return;
  9039. }
  9040. Tools._StartUserMark(counterName, condition);
  9041. if (console.time) {
  9042. console.time(counterName);
  9043. }
  9044. };
  9045. Tools._EndPerformanceConsole = function (counterName, condition) {
  9046. if (condition === void 0) { condition = true; }
  9047. if (!condition) {
  9048. return;
  9049. }
  9050. Tools._EndUserMark(counterName, condition);
  9051. if (console.time) {
  9052. console.timeEnd(counterName);
  9053. }
  9054. };
  9055. Object.defineProperty(Tools, "Now", {
  9056. get: function () {
  9057. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9058. return window.performance.now();
  9059. }
  9060. return new Date().getTime();
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. /**
  9066. * This method will return the name of the class used to create the instance of the given object.
  9067. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9068. * @param object the object to get the class name from
  9069. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9070. */
  9071. Tools.GetClassName = function (object, isType) {
  9072. if (isType === void 0) { isType = false; }
  9073. var name = null;
  9074. if (!isType && object.getClassName) {
  9075. name = object.getClassName();
  9076. }
  9077. else {
  9078. if (object instanceof Object) {
  9079. var classObj = isType ? object : Object.getPrototypeOf(object);
  9080. name = classObj.constructor["__bjsclassName__"];
  9081. }
  9082. if (!name) {
  9083. name = typeof object;
  9084. }
  9085. }
  9086. return name;
  9087. };
  9088. Tools.First = function (array, predicate) {
  9089. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9090. var el = array_1[_i];
  9091. if (predicate(el)) {
  9092. return el;
  9093. }
  9094. }
  9095. return null;
  9096. };
  9097. /**
  9098. * This method will return the name of the full name of the class, including its owning module (if any).
  9099. * 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).
  9100. * @param object the object to get the class name from
  9101. * @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.
  9102. */
  9103. Tools.getFullClassName = function (object, isType) {
  9104. if (isType === void 0) { isType = false; }
  9105. var className = null;
  9106. var moduleName = null;
  9107. if (!isType && object.getClassName) {
  9108. className = object.getClassName();
  9109. }
  9110. else {
  9111. if (object instanceof Object) {
  9112. var classObj = isType ? object : Object.getPrototypeOf(object);
  9113. className = classObj.constructor["__bjsclassName__"];
  9114. moduleName = classObj.constructor["__bjsmoduleName__"];
  9115. }
  9116. if (!className) {
  9117. className = typeof object;
  9118. }
  9119. }
  9120. if (!className) {
  9121. return null;
  9122. }
  9123. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9124. };
  9125. /**
  9126. * 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.
  9127. * @param array
  9128. */
  9129. Tools.arrayOrStringFeeder = function (array) {
  9130. return function (index) {
  9131. if (index >= array.length) {
  9132. return null;
  9133. }
  9134. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9135. if (val && val.getHashCode) {
  9136. val = val.getHashCode();
  9137. }
  9138. if (typeof val === "string") {
  9139. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9140. }
  9141. return val;
  9142. };
  9143. };
  9144. /**
  9145. * Compute the hashCode of a stream of number
  9146. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9147. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9148. * @return the hash code computed
  9149. */
  9150. Tools.hashCodeFromStream = function (feeder) {
  9151. // Based from here: http://stackoverflow.com/a/7616484/802124
  9152. var hash = 0;
  9153. var index = 0;
  9154. var chr = feeder(index++);
  9155. while (chr != null) {
  9156. hash = ((hash << 5) - hash) + chr;
  9157. hash |= 0; // Convert to 32bit integer
  9158. chr = feeder(index++);
  9159. }
  9160. return hash;
  9161. };
  9162. /**
  9163. * Returns a promise that resolves after the given amount of time.
  9164. * @param delay Number of milliseconds to delay
  9165. * @returns Promise that resolves after the given amount of time
  9166. */
  9167. Tools.DelayAsync = function (delay) {
  9168. return new Promise(function (resolve) {
  9169. setTimeout(function () {
  9170. resolve();
  9171. }, delay);
  9172. });
  9173. };
  9174. Tools.BaseUrl = "";
  9175. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9176. /**
  9177. * Default behaviour for cors in the application.
  9178. * It can be a string if the expected behavior is identical in the entire app.
  9179. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9180. */
  9181. Tools.CorsBehavior = "anonymous";
  9182. Tools.UseFallbackTexture = true;
  9183. /**
  9184. * Use this object to register external classes like custom textures or material
  9185. * to allow the laoders to instantiate them
  9186. */
  9187. Tools.RegisteredExternalClasses = {};
  9188. // Used in case of a texture loading problem
  9189. 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";
  9190. Tools.PreprocessUrl = function (url) {
  9191. return url;
  9192. };
  9193. // Logs
  9194. Tools._NoneLogLevel = 0;
  9195. Tools._MessageLogLevel = 1;
  9196. Tools._WarningLogLevel = 2;
  9197. Tools._ErrorLogLevel = 4;
  9198. Tools._LogCache = "";
  9199. Tools.errorsCount = 0;
  9200. Tools.Log = Tools._LogEnabled;
  9201. Tools.Warn = Tools._WarnEnabled;
  9202. Tools.Error = Tools._ErrorEnabled;
  9203. // Performances
  9204. Tools._PerformanceNoneLogLevel = 0;
  9205. Tools._PerformanceUserMarkLogLevel = 1;
  9206. Tools._PerformanceConsoleLogLevel = 2;
  9207. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9208. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9209. return Tools;
  9210. }());
  9211. BABYLON.Tools = Tools;
  9212. /**
  9213. * This class is used to track a performance counter which is number based.
  9214. * The user has access to many properties which give statistics of different nature
  9215. *
  9216. * The implementer can track two kinds of Performance Counter: time and count
  9217. * 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.
  9218. * 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.
  9219. */
  9220. var PerfCounter = /** @class */ (function () {
  9221. function PerfCounter() {
  9222. this._startMonitoringTime = 0;
  9223. this._min = 0;
  9224. this._max = 0;
  9225. this._average = 0;
  9226. this._lastSecAverage = 0;
  9227. this._current = 0;
  9228. this._totalValueCount = 0;
  9229. this._totalAccumulated = 0;
  9230. this._lastSecAccumulated = 0;
  9231. this._lastSecTime = 0;
  9232. this._lastSecValueCount = 0;
  9233. }
  9234. Object.defineProperty(PerfCounter.prototype, "min", {
  9235. /**
  9236. * Returns the smallest value ever
  9237. */
  9238. get: function () {
  9239. return this._min;
  9240. },
  9241. enumerable: true,
  9242. configurable: true
  9243. });
  9244. Object.defineProperty(PerfCounter.prototype, "max", {
  9245. /**
  9246. * Returns the biggest value ever
  9247. */
  9248. get: function () {
  9249. return this._max;
  9250. },
  9251. enumerable: true,
  9252. configurable: true
  9253. });
  9254. Object.defineProperty(PerfCounter.prototype, "average", {
  9255. /**
  9256. * Returns the average value since the performance counter is running
  9257. */
  9258. get: function () {
  9259. return this._average;
  9260. },
  9261. enumerable: true,
  9262. configurable: true
  9263. });
  9264. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9265. /**
  9266. * Returns the average value of the last second the counter was monitored
  9267. */
  9268. get: function () {
  9269. return this._lastSecAverage;
  9270. },
  9271. enumerable: true,
  9272. configurable: true
  9273. });
  9274. Object.defineProperty(PerfCounter.prototype, "current", {
  9275. /**
  9276. * Returns the current value
  9277. */
  9278. get: function () {
  9279. return this._current;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(PerfCounter.prototype, "total", {
  9285. get: function () {
  9286. return this._totalAccumulated;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(PerfCounter.prototype, "count", {
  9292. get: function () {
  9293. return this._totalValueCount;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. /**
  9299. * Call this method to start monitoring a new frame.
  9300. * 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.
  9301. */
  9302. PerfCounter.prototype.fetchNewFrame = function () {
  9303. this._totalValueCount++;
  9304. this._current = 0;
  9305. this._lastSecValueCount++;
  9306. };
  9307. /**
  9308. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9309. * @param newCount the count value to add to the monitored count
  9310. * @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.
  9311. */
  9312. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9313. if (!PerfCounter.Enabled) {
  9314. return;
  9315. }
  9316. this._current += newCount;
  9317. if (fetchResult) {
  9318. this._fetchResult();
  9319. }
  9320. };
  9321. /**
  9322. * Start monitoring this performance counter
  9323. */
  9324. PerfCounter.prototype.beginMonitoring = function () {
  9325. if (!PerfCounter.Enabled) {
  9326. return;
  9327. }
  9328. this._startMonitoringTime = Tools.Now;
  9329. };
  9330. /**
  9331. * Compute the time lapsed since the previous beginMonitoring() call.
  9332. * @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
  9333. */
  9334. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9335. if (newFrame === void 0) { newFrame = true; }
  9336. if (!PerfCounter.Enabled) {
  9337. return;
  9338. }
  9339. if (newFrame) {
  9340. this.fetchNewFrame();
  9341. }
  9342. var currentTime = Tools.Now;
  9343. this._current = currentTime - this._startMonitoringTime;
  9344. if (newFrame) {
  9345. this._fetchResult();
  9346. }
  9347. };
  9348. PerfCounter.prototype._fetchResult = function () {
  9349. this._totalAccumulated += this._current;
  9350. this._lastSecAccumulated += this._current;
  9351. // Min/Max update
  9352. this._min = Math.min(this._min, this._current);
  9353. this._max = Math.max(this._max, this._current);
  9354. this._average = this._totalAccumulated / this._totalValueCount;
  9355. // Reset last sec?
  9356. var now = Tools.Now;
  9357. if ((now - this._lastSecTime) > 1000) {
  9358. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9359. this._lastSecTime = now;
  9360. this._lastSecAccumulated = 0;
  9361. this._lastSecValueCount = 0;
  9362. }
  9363. };
  9364. PerfCounter.Enabled = true;
  9365. return PerfCounter;
  9366. }());
  9367. BABYLON.PerfCounter = PerfCounter;
  9368. /**
  9369. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9370. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9371. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9372. * @param name The name of the class, case should be preserved
  9373. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9374. */
  9375. function className(name, module) {
  9376. return function (target) {
  9377. target["__bjsclassName__"] = name;
  9378. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9379. };
  9380. }
  9381. BABYLON.className = className;
  9382. /**
  9383. * An implementation of a loop for asynchronous functions.
  9384. */
  9385. var AsyncLoop = /** @class */ (function () {
  9386. /**
  9387. * Constroctor.
  9388. * @param iterations the number of iterations.
  9389. * @param _fn the function to run each iteration
  9390. * @param _successCallback the callback that will be called upon succesful execution
  9391. * @param offset starting offset.
  9392. */
  9393. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9394. if (offset === void 0) { offset = 0; }
  9395. this.iterations = iterations;
  9396. this._fn = _fn;
  9397. this._successCallback = _successCallback;
  9398. this.index = offset - 1;
  9399. this._done = false;
  9400. }
  9401. /**
  9402. * Execute the next iteration. Must be called after the last iteration was finished.
  9403. */
  9404. AsyncLoop.prototype.executeNext = function () {
  9405. if (!this._done) {
  9406. if (this.index + 1 < this.iterations) {
  9407. ++this.index;
  9408. this._fn(this);
  9409. }
  9410. else {
  9411. this.breakLoop();
  9412. }
  9413. }
  9414. };
  9415. /**
  9416. * Break the loop and run the success callback.
  9417. */
  9418. AsyncLoop.prototype.breakLoop = function () {
  9419. this._done = true;
  9420. this._successCallback();
  9421. };
  9422. /**
  9423. * Helper function
  9424. */
  9425. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9426. if (offset === void 0) { offset = 0; }
  9427. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9428. loop.executeNext();
  9429. return loop;
  9430. };
  9431. /**
  9432. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9433. * @param iterations total number of iterations
  9434. * @param syncedIterations number of synchronous iterations in each async iteration.
  9435. * @param fn the function to call each iteration.
  9436. * @param callback a success call back that will be called when iterating stops.
  9437. * @param breakFunction a break condition (optional)
  9438. * @param timeout timeout settings for the setTimeout function. default - 0.
  9439. * @constructor
  9440. */
  9441. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9442. if (timeout === void 0) { timeout = 0; }
  9443. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9444. if (breakFunction && breakFunction())
  9445. loop.breakLoop();
  9446. else {
  9447. setTimeout(function () {
  9448. for (var i = 0; i < syncedIterations; ++i) {
  9449. var iteration = (loop.index * syncedIterations) + i;
  9450. if (iteration >= iterations)
  9451. break;
  9452. fn(iteration);
  9453. if (breakFunction && breakFunction()) {
  9454. loop.breakLoop();
  9455. break;
  9456. }
  9457. }
  9458. loop.executeNext();
  9459. }, timeout);
  9460. }
  9461. }, callback);
  9462. };
  9463. return AsyncLoop;
  9464. }());
  9465. BABYLON.AsyncLoop = AsyncLoop;
  9466. })(BABYLON || (BABYLON = {}));
  9467. //# sourceMappingURL=babylon.tools.js.map
  9468. "use strict";
  9469. var BABYLON;
  9470. (function (BABYLON) {
  9471. var PromiseStates;
  9472. (function (PromiseStates) {
  9473. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9474. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9475. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9476. })(PromiseStates || (PromiseStates = {}));
  9477. var FulFillmentAgregator = /** @class */ (function () {
  9478. function FulFillmentAgregator() {
  9479. this.count = 0;
  9480. this.target = 0;
  9481. this.results = [];
  9482. }
  9483. return FulFillmentAgregator;
  9484. }());
  9485. var InternalPromise = /** @class */ (function () {
  9486. function InternalPromise(resolver) {
  9487. var _this = this;
  9488. this._state = PromiseStates.Pending;
  9489. this._children = new Array();
  9490. this._rejectWasConsumed = false;
  9491. if (!resolver) {
  9492. return;
  9493. }
  9494. try {
  9495. resolver(function (value) {
  9496. _this._resolve(value);
  9497. }, function (reason) {
  9498. _this._reject(reason);
  9499. });
  9500. }
  9501. catch (e) {
  9502. this._reject(e);
  9503. }
  9504. }
  9505. InternalPromise.prototype.catch = function (onRejected) {
  9506. return this.then(undefined, onRejected);
  9507. };
  9508. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9509. var _this = this;
  9510. var newPromise = new InternalPromise();
  9511. newPromise._onFulfilled = onFulfilled;
  9512. newPromise._onRejected = onRejected;
  9513. // Composition
  9514. this._children.push(newPromise);
  9515. if (this._state !== PromiseStates.Pending) {
  9516. BABYLON.Tools.SetImmediate(function () {
  9517. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9518. var returnedValue = newPromise._resolve(_this._result);
  9519. if (returnedValue !== undefined && returnedValue !== null) {
  9520. if (returnedValue._state !== undefined) {
  9521. var returnedPromise = returnedValue;
  9522. newPromise._children.push(returnedPromise);
  9523. newPromise = returnedPromise;
  9524. }
  9525. else {
  9526. newPromise._result = returnedValue;
  9527. }
  9528. }
  9529. }
  9530. else {
  9531. newPromise._reject(_this._reason);
  9532. }
  9533. });
  9534. }
  9535. return newPromise;
  9536. };
  9537. InternalPromise.prototype._moveChildren = function (children) {
  9538. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9539. if (this._state === PromiseStates.Fulfilled) {
  9540. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9541. var child = _b[_i];
  9542. child._resolve(this._result);
  9543. }
  9544. }
  9545. else if (this._state === PromiseStates.Rejected) {
  9546. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9547. var child = _d[_c];
  9548. child._reject(this._reason);
  9549. }
  9550. }
  9551. var _a;
  9552. };
  9553. InternalPromise.prototype._resolve = function (value) {
  9554. try {
  9555. this._state = PromiseStates.Fulfilled;
  9556. var returnedValue = null;
  9557. if (this._onFulfilled) {
  9558. returnedValue = this._onFulfilled(value);
  9559. }
  9560. if (returnedValue !== undefined && returnedValue !== null) {
  9561. if (returnedValue._state !== undefined) {
  9562. // Transmit children
  9563. var returnedPromise = returnedValue;
  9564. returnedPromise._moveChildren(this._children);
  9565. value = returnedPromise._result;
  9566. }
  9567. else {
  9568. value = returnedValue;
  9569. }
  9570. }
  9571. this._result = value;
  9572. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9573. var child = _a[_i];
  9574. child._resolve(value);
  9575. }
  9576. this._children.length = 0;
  9577. delete this._onFulfilled;
  9578. delete this._onRejected;
  9579. }
  9580. catch (e) {
  9581. this._reject(e, true);
  9582. }
  9583. };
  9584. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9585. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9586. this._state = PromiseStates.Rejected;
  9587. this._reason = reason;
  9588. if (this._onRejected && !onLocalThrow) {
  9589. try {
  9590. this._onRejected(reason);
  9591. this._rejectWasConsumed = true;
  9592. }
  9593. catch (e) {
  9594. reason = e;
  9595. }
  9596. }
  9597. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9598. var child = _a[_i];
  9599. if (this._rejectWasConsumed) {
  9600. child._resolve(null);
  9601. }
  9602. else {
  9603. child._reject(reason);
  9604. }
  9605. }
  9606. this._children.length = 0;
  9607. delete this._onFulfilled;
  9608. delete this._onRejected;
  9609. };
  9610. InternalPromise.resolve = function (value) {
  9611. var newPromise = new InternalPromise();
  9612. newPromise._resolve(value);
  9613. return newPromise;
  9614. };
  9615. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9616. promise.then(function (value) {
  9617. agregator.results[index] = value;
  9618. agregator.count++;
  9619. if (agregator.count === agregator.target) {
  9620. agregator.rootPromise._resolve(agregator.results);
  9621. }
  9622. return null;
  9623. }, function (reason) {
  9624. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9625. agregator.rootPromise._reject(reason);
  9626. }
  9627. });
  9628. };
  9629. InternalPromise.all = function (promises) {
  9630. var newPromise = new InternalPromise();
  9631. var agregator = new FulFillmentAgregator();
  9632. agregator.target = promises.length;
  9633. agregator.rootPromise = newPromise;
  9634. if (promises.length) {
  9635. for (var index = 0; index < promises.length; index++) {
  9636. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9637. }
  9638. }
  9639. else {
  9640. newPromise._resolve([]);
  9641. }
  9642. return newPromise;
  9643. };
  9644. InternalPromise.race = function (promises) {
  9645. var newPromise = new InternalPromise();
  9646. if (promises.length) {
  9647. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9648. var promise = promises_1[_i];
  9649. promise.then(function (value) {
  9650. if (newPromise) {
  9651. newPromise._resolve(value);
  9652. newPromise = null;
  9653. }
  9654. return null;
  9655. }, function (reason) {
  9656. if (newPromise) {
  9657. newPromise._reject(reason);
  9658. newPromise = null;
  9659. }
  9660. });
  9661. }
  9662. }
  9663. return newPromise;
  9664. };
  9665. return InternalPromise;
  9666. }());
  9667. /**
  9668. * Helper class that provides a small promise polyfill
  9669. */
  9670. var PromisePolyfill = /** @class */ (function () {
  9671. function PromisePolyfill() {
  9672. }
  9673. /**
  9674. * Static function used to check if the polyfill is required
  9675. * If this is the case then the function will inject the polyfill to window.Promise
  9676. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9677. */
  9678. PromisePolyfill.Apply = function (force) {
  9679. if (force === void 0) { force = false; }
  9680. if (force || typeof Promise === 'undefined') {
  9681. var root = window;
  9682. root.Promise = InternalPromise;
  9683. }
  9684. };
  9685. return PromisePolyfill;
  9686. }());
  9687. BABYLON.PromisePolyfill = PromisePolyfill;
  9688. })(BABYLON || (BABYLON = {}));
  9689. //# sourceMappingURL=babylon.promise.js.map
  9690. "use strict";
  9691. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9692. var BABYLON;
  9693. (function (BABYLON) {
  9694. /**
  9695. * Helper class to push actions to a pool of workers.
  9696. */
  9697. var WorkerPool = /** @class */ (function () {
  9698. /**
  9699. * Constructor
  9700. * @param workers Array of workers to use for actions
  9701. */
  9702. function WorkerPool(workers) {
  9703. this._pendingActions = new Array();
  9704. this._workerInfos = workers.map(function (worker) { return ({
  9705. worker: worker,
  9706. active: false
  9707. }); });
  9708. }
  9709. /**
  9710. * Terminates all workers and clears any pending actions.
  9711. */
  9712. WorkerPool.prototype.dispose = function () {
  9713. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9714. var workerInfo = _a[_i];
  9715. workerInfo.worker.terminate();
  9716. }
  9717. delete this._workerInfos;
  9718. delete this._pendingActions;
  9719. };
  9720. /**
  9721. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9722. * pended until a worker has completed its action.
  9723. * @param action The action to perform. Call onComplete when the action is complete.
  9724. */
  9725. WorkerPool.prototype.push = function (action) {
  9726. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9727. var workerInfo = _a[_i];
  9728. if (!workerInfo.active) {
  9729. this._execute(workerInfo, action);
  9730. return;
  9731. }
  9732. }
  9733. this._pendingActions.push(action);
  9734. };
  9735. WorkerPool.prototype._execute = function (workerInfo, action) {
  9736. var _this = this;
  9737. workerInfo.active = true;
  9738. action(workerInfo.worker, function () {
  9739. workerInfo.active = false;
  9740. var nextAction = _this._pendingActions.shift();
  9741. if (nextAction) {
  9742. _this._execute(workerInfo, nextAction);
  9743. }
  9744. });
  9745. };
  9746. return WorkerPool;
  9747. }());
  9748. BABYLON.WorkerPool = WorkerPool;
  9749. })(BABYLON || (BABYLON = {}));
  9750. //# sourceMappingURL=babylon.workerPool.js.map
  9751. "use strict";
  9752. var BABYLON;
  9753. (function (BABYLON) {
  9754. var _AlphaState = /** @class */ (function () {
  9755. /**
  9756. * Initializes the state.
  9757. */
  9758. function _AlphaState() {
  9759. this._isAlphaBlendDirty = false;
  9760. this._isBlendFunctionParametersDirty = false;
  9761. this._isBlendEquationParametersDirty = false;
  9762. this._isBlendConstantsDirty = false;
  9763. this._alphaBlend = false;
  9764. this._blendFunctionParameters = new Array(4);
  9765. this._blendEquationParameters = new Array(2);
  9766. this._blendConstants = new Array(4);
  9767. this.reset();
  9768. }
  9769. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9770. get: function () {
  9771. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9777. get: function () {
  9778. return this._alphaBlend;
  9779. },
  9780. set: function (value) {
  9781. if (this._alphaBlend === value) {
  9782. return;
  9783. }
  9784. this._alphaBlend = value;
  9785. this._isAlphaBlendDirty = true;
  9786. },
  9787. enumerable: true,
  9788. configurable: true
  9789. });
  9790. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9791. if (this._blendConstants[0] === r &&
  9792. this._blendConstants[1] === g &&
  9793. this._blendConstants[2] === b &&
  9794. this._blendConstants[3] === a) {
  9795. return;
  9796. }
  9797. this._blendConstants[0] = r;
  9798. this._blendConstants[1] = g;
  9799. this._blendConstants[2] = b;
  9800. this._blendConstants[3] = a;
  9801. this._isBlendConstantsDirty = true;
  9802. };
  9803. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9804. if (this._blendFunctionParameters[0] === value0 &&
  9805. this._blendFunctionParameters[1] === value1 &&
  9806. this._blendFunctionParameters[2] === value2 &&
  9807. this._blendFunctionParameters[3] === value3) {
  9808. return;
  9809. }
  9810. this._blendFunctionParameters[0] = value0;
  9811. this._blendFunctionParameters[1] = value1;
  9812. this._blendFunctionParameters[2] = value2;
  9813. this._blendFunctionParameters[3] = value3;
  9814. this._isBlendFunctionParametersDirty = true;
  9815. };
  9816. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9817. if (this._blendEquationParameters[0] === rgb &&
  9818. this._blendEquationParameters[1] === alpha) {
  9819. return;
  9820. }
  9821. this._blendEquationParameters[0] = rgb;
  9822. this._blendEquationParameters[1] = alpha;
  9823. this._isBlendEquationParametersDirty = true;
  9824. };
  9825. _AlphaState.prototype.reset = function () {
  9826. this._alphaBlend = false;
  9827. this._blendFunctionParameters[0] = null;
  9828. this._blendFunctionParameters[1] = null;
  9829. this._blendFunctionParameters[2] = null;
  9830. this._blendFunctionParameters[3] = null;
  9831. this._blendEquationParameters[0] = null;
  9832. this._blendEquationParameters[1] = null;
  9833. this._blendConstants[0] = null;
  9834. this._blendConstants[1] = null;
  9835. this._blendConstants[2] = null;
  9836. this._blendConstants[3] = null;
  9837. this._isAlphaBlendDirty = true;
  9838. this._isBlendFunctionParametersDirty = false;
  9839. this._isBlendEquationParametersDirty = false;
  9840. this._isBlendConstantsDirty = false;
  9841. };
  9842. _AlphaState.prototype.apply = function (gl) {
  9843. if (!this.isDirty) {
  9844. return;
  9845. }
  9846. // Alpha blend
  9847. if (this._isAlphaBlendDirty) {
  9848. if (this._alphaBlend) {
  9849. gl.enable(gl.BLEND);
  9850. }
  9851. else {
  9852. gl.disable(gl.BLEND);
  9853. }
  9854. this._isAlphaBlendDirty = false;
  9855. }
  9856. // Alpha function
  9857. if (this._isBlendFunctionParametersDirty) {
  9858. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9859. this._isBlendFunctionParametersDirty = false;
  9860. }
  9861. // Alpha equation
  9862. if (this._isBlendEquationParametersDirty) {
  9863. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9864. this._isBlendEquationParametersDirty = false;
  9865. }
  9866. // Constants
  9867. if (this._isBlendConstantsDirty) {
  9868. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9869. this._isBlendConstantsDirty = false;
  9870. }
  9871. };
  9872. return _AlphaState;
  9873. }());
  9874. BABYLON._AlphaState = _AlphaState;
  9875. })(BABYLON || (BABYLON = {}));
  9876. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9877. "use strict";
  9878. var BABYLON;
  9879. (function (BABYLON) {
  9880. var _DepthCullingState = /** @class */ (function () {
  9881. /**
  9882. * Initializes the state.
  9883. */
  9884. function _DepthCullingState() {
  9885. this._isDepthTestDirty = false;
  9886. this._isDepthMaskDirty = false;
  9887. this._isDepthFuncDirty = false;
  9888. this._isCullFaceDirty = false;
  9889. this._isCullDirty = false;
  9890. this._isZOffsetDirty = false;
  9891. this._isFrontFaceDirty = false;
  9892. this.reset();
  9893. }
  9894. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9895. get: function () {
  9896. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9902. get: function () {
  9903. return this._zOffset;
  9904. },
  9905. set: function (value) {
  9906. if (this._zOffset === value) {
  9907. return;
  9908. }
  9909. this._zOffset = value;
  9910. this._isZOffsetDirty = true;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9916. get: function () {
  9917. return this._cullFace;
  9918. },
  9919. set: function (value) {
  9920. if (this._cullFace === value) {
  9921. return;
  9922. }
  9923. this._cullFace = value;
  9924. this._isCullFaceDirty = true;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9930. get: function () {
  9931. return this._cull;
  9932. },
  9933. set: function (value) {
  9934. if (this._cull === value) {
  9935. return;
  9936. }
  9937. this._cull = value;
  9938. this._isCullDirty = true;
  9939. },
  9940. enumerable: true,
  9941. configurable: true
  9942. });
  9943. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9944. get: function () {
  9945. return this._depthFunc;
  9946. },
  9947. set: function (value) {
  9948. if (this._depthFunc === value) {
  9949. return;
  9950. }
  9951. this._depthFunc = value;
  9952. this._isDepthFuncDirty = true;
  9953. },
  9954. enumerable: true,
  9955. configurable: true
  9956. });
  9957. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9958. get: function () {
  9959. return this._depthMask;
  9960. },
  9961. set: function (value) {
  9962. if (this._depthMask === value) {
  9963. return;
  9964. }
  9965. this._depthMask = value;
  9966. this._isDepthMaskDirty = true;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9972. get: function () {
  9973. return this._depthTest;
  9974. },
  9975. set: function (value) {
  9976. if (this._depthTest === value) {
  9977. return;
  9978. }
  9979. this._depthTest = value;
  9980. this._isDepthTestDirty = true;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9986. get: function () {
  9987. return this._frontFace;
  9988. },
  9989. set: function (value) {
  9990. if (this._frontFace === value) {
  9991. return;
  9992. }
  9993. this._frontFace = value;
  9994. this._isFrontFaceDirty = true;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. _DepthCullingState.prototype.reset = function () {
  10000. this._depthMask = true;
  10001. this._depthTest = true;
  10002. this._depthFunc = null;
  10003. this._cullFace = null;
  10004. this._cull = null;
  10005. this._zOffset = 0;
  10006. this._frontFace = null;
  10007. this._isDepthTestDirty = true;
  10008. this._isDepthMaskDirty = true;
  10009. this._isDepthFuncDirty = false;
  10010. this._isCullFaceDirty = false;
  10011. this._isCullDirty = false;
  10012. this._isZOffsetDirty = false;
  10013. this._isFrontFaceDirty = false;
  10014. };
  10015. _DepthCullingState.prototype.apply = function (gl) {
  10016. if (!this.isDirty) {
  10017. return;
  10018. }
  10019. // Cull
  10020. if (this._isCullDirty) {
  10021. if (this.cull) {
  10022. gl.enable(gl.CULL_FACE);
  10023. }
  10024. else {
  10025. gl.disable(gl.CULL_FACE);
  10026. }
  10027. this._isCullDirty = false;
  10028. }
  10029. // Cull face
  10030. if (this._isCullFaceDirty) {
  10031. gl.cullFace(this.cullFace);
  10032. this._isCullFaceDirty = false;
  10033. }
  10034. // Depth mask
  10035. if (this._isDepthMaskDirty) {
  10036. gl.depthMask(this.depthMask);
  10037. this._isDepthMaskDirty = false;
  10038. }
  10039. // Depth test
  10040. if (this._isDepthTestDirty) {
  10041. if (this.depthTest) {
  10042. gl.enable(gl.DEPTH_TEST);
  10043. }
  10044. else {
  10045. gl.disable(gl.DEPTH_TEST);
  10046. }
  10047. this._isDepthTestDirty = false;
  10048. }
  10049. // Depth func
  10050. if (this._isDepthFuncDirty) {
  10051. gl.depthFunc(this.depthFunc);
  10052. this._isDepthFuncDirty = false;
  10053. }
  10054. // zOffset
  10055. if (this._isZOffsetDirty) {
  10056. if (this.zOffset) {
  10057. gl.enable(gl.POLYGON_OFFSET_FILL);
  10058. gl.polygonOffset(this.zOffset, 0);
  10059. }
  10060. else {
  10061. gl.disable(gl.POLYGON_OFFSET_FILL);
  10062. }
  10063. this._isZOffsetDirty = false;
  10064. }
  10065. // Front face
  10066. if (this._isFrontFaceDirty) {
  10067. gl.frontFace(this.frontFace);
  10068. this._isFrontFaceDirty = false;
  10069. }
  10070. };
  10071. return _DepthCullingState;
  10072. }());
  10073. BABYLON._DepthCullingState = _DepthCullingState;
  10074. })(BABYLON || (BABYLON = {}));
  10075. //# sourceMappingURL=babylon.depthCullingState.js.map
  10076. "use strict";
  10077. var BABYLON;
  10078. (function (BABYLON) {
  10079. var _StencilState = /** @class */ (function () {
  10080. function _StencilState() {
  10081. this._isStencilTestDirty = false;
  10082. this._isStencilMaskDirty = false;
  10083. this._isStencilFuncDirty = false;
  10084. this._isStencilOpDirty = false;
  10085. this.reset();
  10086. }
  10087. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10088. get: function () {
  10089. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10095. get: function () {
  10096. return this._stencilFunc;
  10097. },
  10098. set: function (value) {
  10099. if (this._stencilFunc === value) {
  10100. return;
  10101. }
  10102. this._stencilFunc = value;
  10103. this._isStencilFuncDirty = true;
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10109. get: function () {
  10110. return this._stencilFuncRef;
  10111. },
  10112. set: function (value) {
  10113. if (this._stencilFuncRef === value) {
  10114. return;
  10115. }
  10116. this._stencilFuncRef = value;
  10117. this._isStencilFuncDirty = true;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10123. get: function () {
  10124. return this._stencilFuncMask;
  10125. },
  10126. set: function (value) {
  10127. if (this._stencilFuncMask === value) {
  10128. return;
  10129. }
  10130. this._stencilFuncMask = value;
  10131. this._isStencilFuncDirty = true;
  10132. },
  10133. enumerable: true,
  10134. configurable: true
  10135. });
  10136. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10137. get: function () {
  10138. return this._stencilOpStencilFail;
  10139. },
  10140. set: function (value) {
  10141. if (this._stencilOpStencilFail === value) {
  10142. return;
  10143. }
  10144. this._stencilOpStencilFail = value;
  10145. this._isStencilOpDirty = true;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10151. get: function () {
  10152. return this._stencilOpDepthFail;
  10153. },
  10154. set: function (value) {
  10155. if (this._stencilOpDepthFail === value) {
  10156. return;
  10157. }
  10158. this._stencilOpDepthFail = value;
  10159. this._isStencilOpDirty = true;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10165. get: function () {
  10166. return this._stencilOpStencilDepthPass;
  10167. },
  10168. set: function (value) {
  10169. if (this._stencilOpStencilDepthPass === value) {
  10170. return;
  10171. }
  10172. this._stencilOpStencilDepthPass = value;
  10173. this._isStencilOpDirty = true;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10179. get: function () {
  10180. return this._stencilMask;
  10181. },
  10182. set: function (value) {
  10183. if (this._stencilMask === value) {
  10184. return;
  10185. }
  10186. this._stencilMask = value;
  10187. this._isStencilMaskDirty = true;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10193. get: function () {
  10194. return this._stencilTest;
  10195. },
  10196. set: function (value) {
  10197. if (this._stencilTest === value) {
  10198. return;
  10199. }
  10200. this._stencilTest = value;
  10201. this._isStencilTestDirty = true;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. _StencilState.prototype.reset = function () {
  10207. this._stencilTest = false;
  10208. this._stencilMask = 0xFF;
  10209. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10210. this._stencilFuncRef = 1;
  10211. this._stencilFuncMask = 0xFF;
  10212. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10213. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10214. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10215. this._isStencilTestDirty = true;
  10216. this._isStencilMaskDirty = true;
  10217. this._isStencilFuncDirty = true;
  10218. this._isStencilOpDirty = true;
  10219. };
  10220. _StencilState.prototype.apply = function (gl) {
  10221. if (!this.isDirty) {
  10222. return;
  10223. }
  10224. // Stencil test
  10225. if (this._isStencilTestDirty) {
  10226. if (this.stencilTest) {
  10227. gl.enable(gl.STENCIL_TEST);
  10228. }
  10229. else {
  10230. gl.disable(gl.STENCIL_TEST);
  10231. }
  10232. this._isStencilTestDirty = false;
  10233. }
  10234. // Stencil mask
  10235. if (this._isStencilMaskDirty) {
  10236. gl.stencilMask(this.stencilMask);
  10237. this._isStencilMaskDirty = false;
  10238. }
  10239. // Stencil func
  10240. if (this._isStencilFuncDirty) {
  10241. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10242. this._isStencilFuncDirty = false;
  10243. }
  10244. // Stencil op
  10245. if (this._isStencilOpDirty) {
  10246. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10247. this._isStencilOpDirty = false;
  10248. }
  10249. };
  10250. return _StencilState;
  10251. }());
  10252. BABYLON._StencilState = _StencilState;
  10253. })(BABYLON || (BABYLON = {}));
  10254. //# sourceMappingURL=babylon.stencilState.js.map
  10255. "use strict";
  10256. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10257. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10258. s = arguments[i];
  10259. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10260. t[p] = s[p];
  10261. }
  10262. return t;
  10263. };
  10264. var BABYLON;
  10265. (function (BABYLON) {
  10266. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10267. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10268. };
  10269. var compileRawShader = function (gl, source, type) {
  10270. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10271. gl.shaderSource(shader, source);
  10272. gl.compileShader(shader);
  10273. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10274. var log = gl.getShaderInfoLog(shader);
  10275. if (log) {
  10276. throw new Error(log);
  10277. }
  10278. }
  10279. if (!shader) {
  10280. throw new Error("Something went wrong while compile the shader.");
  10281. }
  10282. return shader;
  10283. };
  10284. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10285. var magFilter = gl.NEAREST;
  10286. var minFilter = gl.NEAREST;
  10287. switch (samplingMode) {
  10288. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10289. magFilter = gl.LINEAR;
  10290. if (generateMipMaps) {
  10291. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10292. }
  10293. else {
  10294. minFilter = gl.LINEAR;
  10295. }
  10296. break;
  10297. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10298. magFilter = gl.LINEAR;
  10299. if (generateMipMaps) {
  10300. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10301. }
  10302. else {
  10303. minFilter = gl.LINEAR;
  10304. }
  10305. break;
  10306. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10307. magFilter = gl.NEAREST;
  10308. if (generateMipMaps) {
  10309. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10310. }
  10311. else {
  10312. minFilter = gl.NEAREST;
  10313. }
  10314. break;
  10315. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10316. magFilter = gl.NEAREST;
  10317. if (generateMipMaps) {
  10318. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10319. }
  10320. else {
  10321. minFilter = gl.NEAREST;
  10322. }
  10323. break;
  10324. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10325. magFilter = gl.NEAREST;
  10326. if (generateMipMaps) {
  10327. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10328. }
  10329. else {
  10330. minFilter = gl.LINEAR;
  10331. }
  10332. break;
  10333. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10334. magFilter = gl.NEAREST;
  10335. if (generateMipMaps) {
  10336. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10337. }
  10338. else {
  10339. minFilter = gl.LINEAR;
  10340. }
  10341. break;
  10342. case BABYLON.Texture.NEAREST_LINEAR:
  10343. magFilter = gl.NEAREST;
  10344. minFilter = gl.LINEAR;
  10345. break;
  10346. case BABYLON.Texture.NEAREST_NEAREST:
  10347. magFilter = gl.NEAREST;
  10348. minFilter = gl.NEAREST;
  10349. break;
  10350. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10351. magFilter = gl.LINEAR;
  10352. if (generateMipMaps) {
  10353. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10354. }
  10355. else {
  10356. minFilter = gl.NEAREST;
  10357. }
  10358. break;
  10359. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10360. magFilter = gl.LINEAR;
  10361. if (generateMipMaps) {
  10362. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10363. }
  10364. else {
  10365. minFilter = gl.NEAREST;
  10366. }
  10367. break;
  10368. case BABYLON.Texture.LINEAR_LINEAR:
  10369. magFilter = gl.LINEAR;
  10370. minFilter = gl.LINEAR;
  10371. break;
  10372. case BABYLON.Texture.LINEAR_NEAREST:
  10373. magFilter = gl.LINEAR;
  10374. minFilter = gl.NEAREST;
  10375. break;
  10376. }
  10377. return {
  10378. min: minFilter,
  10379. mag: magFilter
  10380. };
  10381. };
  10382. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10383. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10384. var img;
  10385. var onload = function () {
  10386. loadedImages[index] = img;
  10387. loadedImages._internalCount++;
  10388. if (scene) {
  10389. scene._removePendingData(img);
  10390. }
  10391. if (loadedImages._internalCount === 6) {
  10392. onfinish(loadedImages);
  10393. }
  10394. };
  10395. var onerror = function (message, exception) {
  10396. if (scene) {
  10397. scene._removePendingData(img);
  10398. }
  10399. if (onErrorCallBack) {
  10400. onErrorCallBack(message, exception);
  10401. }
  10402. };
  10403. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10404. if (scene) {
  10405. scene._addPendingData(img);
  10406. }
  10407. };
  10408. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10409. if (onError === void 0) { onError = null; }
  10410. var loadedImages = [];
  10411. loadedImages._internalCount = 0;
  10412. for (var index = 0; index < 6; index++) {
  10413. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10414. }
  10415. };
  10416. var BufferPointer = /** @class */ (function () {
  10417. function BufferPointer() {
  10418. }
  10419. return BufferPointer;
  10420. }());
  10421. var InstancingAttributeInfo = /** @class */ (function () {
  10422. function InstancingAttributeInfo() {
  10423. }
  10424. return InstancingAttributeInfo;
  10425. }());
  10426. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10427. /**
  10428. * Define options used to create a render target texture
  10429. */
  10430. var RenderTargetCreationOptions = /** @class */ (function () {
  10431. function RenderTargetCreationOptions() {
  10432. }
  10433. return RenderTargetCreationOptions;
  10434. }());
  10435. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10436. /**
  10437. * Define options used to create a depth texture
  10438. */
  10439. var DepthTextureCreationOptions = /** @class */ (function () {
  10440. function DepthTextureCreationOptions() {
  10441. }
  10442. return DepthTextureCreationOptions;
  10443. }());
  10444. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10445. /**
  10446. * Regroup several parameters relative to the browser in use
  10447. */
  10448. var EngineCapabilities = /** @class */ (function () {
  10449. function EngineCapabilities() {
  10450. }
  10451. return EngineCapabilities;
  10452. }());
  10453. BABYLON.EngineCapabilities = EngineCapabilities;
  10454. /**
  10455. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10456. */
  10457. var Engine = /** @class */ (function () {
  10458. /**
  10459. * @constructor
  10460. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10461. * @param antialias defines enable antialiasing (default: false)
  10462. * @param options defines further options to be sent to the getContext() function
  10463. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10464. */
  10465. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10466. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10467. var _this = this;
  10468. // Public members
  10469. this.forcePOTTextures = false;
  10470. this.isFullscreen = false;
  10471. this.isPointerLock = false;
  10472. this.cullBackFaces = true;
  10473. this.renderEvenInBackground = true;
  10474. this.preventCacheWipeBetweenFrames = false;
  10475. /**
  10476. * To enable/disable IDB support and avoid XHR on .manifest
  10477. **/
  10478. this.enableOfflineSupport = false;
  10479. this.scenes = new Array();
  10480. this.postProcesses = new Array();
  10481. // Observables
  10482. /**
  10483. * Observable event triggered each time the rendering canvas is resized
  10484. */
  10485. this.onResizeObservable = new BABYLON.Observable();
  10486. /**
  10487. * Observable event triggered each time the canvas loses focus
  10488. */
  10489. this.onCanvasBlurObservable = new BABYLON.Observable();
  10490. /**
  10491. * Observable event triggered each time the canvas gains focus
  10492. */
  10493. this.onCanvasFocusObservable = new BABYLON.Observable();
  10494. /**
  10495. * Observable event triggered each time the canvas receives pointerout event
  10496. */
  10497. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10498. /**
  10499. * Observable event triggered before each texture is initialized
  10500. */
  10501. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10502. //WebVR
  10503. this._vrDisplay = undefined;
  10504. this._vrSupported = false;
  10505. this._vrExclusivePointerMode = false;
  10506. // Uniform buffers list
  10507. this.disableUniformBuffers = false;
  10508. this._uniformBuffers = new Array();
  10509. // Observables
  10510. /**
  10511. * Observable raised when the engine begins a new frame
  10512. */
  10513. this.onBeginFrameObservable = new BABYLON.Observable();
  10514. /**
  10515. * Observable raised when the engine ends the current frame
  10516. */
  10517. this.onEndFrameObservable = new BABYLON.Observable();
  10518. /**
  10519. * Observable raised when the engine is about to compile a shader
  10520. */
  10521. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10522. /**
  10523. * Observable raised when the engine has jsut compiled a shader
  10524. */
  10525. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10526. this._windowIsBackground = false;
  10527. this._webGLVersion = 1.0;
  10528. this._badOS = false;
  10529. this._badDesktopOS = false;
  10530. /**
  10531. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10532. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10533. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10534. */
  10535. this.disableTextureBindingOptimization = false;
  10536. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10537. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10538. this.onVRRequestPresentStart = new BABYLON.Observable();
  10539. this._colorWrite = true;
  10540. this._drawCalls = new BABYLON.PerfCounter();
  10541. this._textureCollisions = new BABYLON.PerfCounter();
  10542. this._renderingQueueLaunched = false;
  10543. this._activeRenderLoops = new Array();
  10544. // Deterministic lockstepMaxSteps
  10545. this._deterministicLockstep = false;
  10546. this._lockstepMaxSteps = 4;
  10547. // Lost context
  10548. this.onContextLostObservable = new BABYLON.Observable();
  10549. this.onContextRestoredObservable = new BABYLON.Observable();
  10550. this._contextWasLost = false;
  10551. this._doNotHandleContextLost = false;
  10552. // FPS
  10553. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10554. this._fps = 60;
  10555. this._deltaTime = 0;
  10556. /**
  10557. * Turn this value on if you want to pause FPS computation when in background
  10558. */
  10559. this.disablePerformanceMonitorInBackground = false;
  10560. // States
  10561. this._depthCullingState = new BABYLON._DepthCullingState();
  10562. this._stencilState = new BABYLON._StencilState();
  10563. this._alphaState = new BABYLON._AlphaState();
  10564. this._alphaMode = Engine.ALPHA_DISABLE;
  10565. // Cache
  10566. this._internalTexturesCache = new Array();
  10567. this._activeChannel = 0;
  10568. this._currentTextureChannel = -1;
  10569. this._boundTexturesCache = {};
  10570. this._compiledEffects = {};
  10571. this._vertexAttribArraysEnabled = [];
  10572. this._uintIndicesCurrentlySet = false;
  10573. this._currentBoundBuffer = new Array();
  10574. this._currentBufferPointers = new Array();
  10575. this._currentInstanceLocations = new Array();
  10576. this._currentInstanceBuffers = new Array();
  10577. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10578. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10579. this._vaoRecordInProgress = false;
  10580. this._mustWipeVertexAttributes = false;
  10581. this._nextFreeTextureSlots = new Array();
  10582. this._maxSimultaneousTextures = 0;
  10583. this._activeRequests = new Array();
  10584. // Hardware supported Compressed Textures
  10585. this._texturesSupported = new Array();
  10586. this._onVRFullScreenTriggered = function () {
  10587. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10588. //get the old size before we change
  10589. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10590. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10591. //get the width and height, change the render size
  10592. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10593. _this.setHardwareScalingLevel(1);
  10594. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10595. }
  10596. else {
  10597. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10598. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10599. }
  10600. };
  10601. this._boundUniforms = {};
  10602. // Register promises
  10603. BABYLON.PromisePolyfill.Apply();
  10604. var canvas = null;
  10605. Engine.Instances.push(this);
  10606. if (!canvasOrContext) {
  10607. return;
  10608. }
  10609. options = options || {};
  10610. if (canvasOrContext.getContext) {
  10611. canvas = canvasOrContext;
  10612. this._renderingCanvas = canvas;
  10613. if (antialias != null) {
  10614. options.antialias = antialias;
  10615. }
  10616. if (options.deterministicLockstep === undefined) {
  10617. options.deterministicLockstep = false;
  10618. }
  10619. if (options.lockstepMaxSteps === undefined) {
  10620. options.lockstepMaxSteps = 4;
  10621. }
  10622. if (options.preserveDrawingBuffer === undefined) {
  10623. options.preserveDrawingBuffer = false;
  10624. }
  10625. if (options.audioEngine === undefined) {
  10626. options.audioEngine = true;
  10627. }
  10628. if (options.stencil === undefined) {
  10629. options.stencil = true;
  10630. }
  10631. this._deterministicLockstep = options.deterministicLockstep;
  10632. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10633. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10634. // Exceptions
  10635. if (navigator && navigator.userAgent) {
  10636. var ua = navigator.userAgent;
  10637. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10638. var exception = _a[_i];
  10639. var key = exception.key;
  10640. var targets = exception.targets;
  10641. if (ua.indexOf(key) > -1) {
  10642. if (exception.capture && exception.captureConstraint) {
  10643. var capture = exception.capture;
  10644. var constraint = exception.captureConstraint;
  10645. var regex = new RegExp(capture);
  10646. var matches = regex.exec(ua);
  10647. if (matches && matches.length > 0) {
  10648. var capturedValue = parseInt(matches[matches.length - 1]);
  10649. if (capturedValue >= constraint) {
  10650. continue;
  10651. }
  10652. }
  10653. }
  10654. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10655. var target = targets_1[_b];
  10656. switch (target) {
  10657. case "uniformBuffer":
  10658. this.disableUniformBuffers = true;
  10659. break;
  10660. case "textureBindingOptimization":
  10661. this.disableTextureBindingOptimization = true;
  10662. break;
  10663. }
  10664. }
  10665. }
  10666. }
  10667. }
  10668. // GL
  10669. if (!options.disableWebGL2Support) {
  10670. try {
  10671. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10672. if (this._gl) {
  10673. this._webGLVersion = 2.0;
  10674. }
  10675. }
  10676. catch (e) {
  10677. // Do nothing
  10678. }
  10679. }
  10680. if (!this._gl) {
  10681. if (!canvas) {
  10682. throw new Error("The provided canvas is null or undefined.");
  10683. }
  10684. try {
  10685. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10686. }
  10687. catch (e) {
  10688. throw new Error("WebGL not supported");
  10689. }
  10690. }
  10691. if (!this._gl) {
  10692. throw new Error("WebGL not supported");
  10693. }
  10694. this._onCanvasFocus = function () {
  10695. _this.onCanvasFocusObservable.notifyObservers(_this);
  10696. };
  10697. this._onCanvasBlur = function () {
  10698. _this.onCanvasBlurObservable.notifyObservers(_this);
  10699. };
  10700. canvas.addEventListener("focus", this._onCanvasFocus);
  10701. canvas.addEventListener("blur", this._onCanvasBlur);
  10702. this._onBlur = function () {
  10703. if (_this.disablePerformanceMonitorInBackground) {
  10704. _this._performanceMonitor.disable();
  10705. }
  10706. _this._windowIsBackground = true;
  10707. };
  10708. this._onFocus = function () {
  10709. if (_this.disablePerformanceMonitorInBackground) {
  10710. _this._performanceMonitor.enable();
  10711. }
  10712. _this._windowIsBackground = false;
  10713. };
  10714. this._onCanvasPointerOut = function (ev) {
  10715. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10716. };
  10717. window.addEventListener("blur", this._onBlur);
  10718. window.addEventListener("focus", this._onFocus);
  10719. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10720. // Context lost
  10721. if (!this._doNotHandleContextLost) {
  10722. this._onContextLost = function (evt) {
  10723. evt.preventDefault();
  10724. _this._contextWasLost = true;
  10725. BABYLON.Tools.Warn("WebGL context lost.");
  10726. _this.onContextLostObservable.notifyObservers(_this);
  10727. };
  10728. this._onContextRestored = function (evt) {
  10729. // Adding a timeout to avoid race condition at browser level
  10730. setTimeout(function () {
  10731. // Rebuild gl context
  10732. _this._initGLContext();
  10733. // Rebuild effects
  10734. _this._rebuildEffects();
  10735. // Rebuild textures
  10736. _this._rebuildInternalTextures();
  10737. // Rebuild buffers
  10738. _this._rebuildBuffers();
  10739. // Cache
  10740. _this.wipeCaches(true);
  10741. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10742. _this.onContextRestoredObservable.notifyObservers(_this);
  10743. _this._contextWasLost = false;
  10744. }, 0);
  10745. };
  10746. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10747. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10748. }
  10749. }
  10750. else {
  10751. this._gl = canvasOrContext;
  10752. this._renderingCanvas = this._gl.canvas;
  10753. if (this._gl.renderbufferStorageMultisample) {
  10754. this._webGLVersion = 2.0;
  10755. }
  10756. options.stencil = this._gl.getContextAttributes().stencil;
  10757. }
  10758. // Viewport
  10759. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10760. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10761. this.resize();
  10762. this._isStencilEnable = options.stencil ? true : false;
  10763. this._initGLContext();
  10764. if (canvas) {
  10765. // Fullscreen
  10766. this._onFullscreenChange = function () {
  10767. if (document.fullscreen !== undefined) {
  10768. _this.isFullscreen = document.fullscreen;
  10769. }
  10770. else if (document.mozFullScreen !== undefined) {
  10771. _this.isFullscreen = document.mozFullScreen;
  10772. }
  10773. else if (document.webkitIsFullScreen !== undefined) {
  10774. _this.isFullscreen = document.webkitIsFullScreen;
  10775. }
  10776. else if (document.msIsFullScreen !== undefined) {
  10777. _this.isFullscreen = document.msIsFullScreen;
  10778. }
  10779. // Pointer lock
  10780. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10781. canvas.requestPointerLock = canvas.requestPointerLock ||
  10782. canvas.msRequestPointerLock ||
  10783. canvas.mozRequestPointerLock ||
  10784. canvas.webkitRequestPointerLock;
  10785. if (canvas.requestPointerLock) {
  10786. canvas.requestPointerLock();
  10787. }
  10788. }
  10789. };
  10790. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10791. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10792. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10793. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10794. // Pointer lock
  10795. this._onPointerLockChange = function () {
  10796. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10797. document.webkitPointerLockElement === canvas ||
  10798. document.msPointerLockElement === canvas ||
  10799. document.pointerLockElement === canvas);
  10800. };
  10801. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10802. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10803. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10804. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10805. this._onVRDisplayPointerRestricted = function () {
  10806. if (canvas) {
  10807. canvas.requestPointerLock();
  10808. }
  10809. };
  10810. this._onVRDisplayPointerUnrestricted = function () {
  10811. document.exitPointerLock();
  10812. };
  10813. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10814. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10815. }
  10816. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10817. Engine.audioEngine = new BABYLON.AudioEngine();
  10818. }
  10819. // Prepare buffer pointers
  10820. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10821. this._currentBufferPointers[i] = new BufferPointer();
  10822. }
  10823. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10824. // Load WebVR Devices
  10825. if (options.autoEnableWebVR) {
  10826. this.initWebVR();
  10827. }
  10828. // Detect if we are running on a faulty buggy OS.
  10829. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10830. // Detect if we are running on a faulty buggy desktop OS.
  10831. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10832. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10833. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10834. }
  10835. Object.defineProperty(Engine, "LastCreatedEngine", {
  10836. get: function () {
  10837. if (Engine.Instances.length === 0) {
  10838. return null;
  10839. }
  10840. return Engine.Instances[Engine.Instances.length - 1];
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(Engine, "LastCreatedScene", {
  10846. get: function () {
  10847. var lastCreatedEngine = Engine.LastCreatedEngine;
  10848. if (!lastCreatedEngine) {
  10849. return null;
  10850. }
  10851. if (lastCreatedEngine.scenes.length === 0) {
  10852. return null;
  10853. }
  10854. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. /**
  10860. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10861. */
  10862. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10863. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10864. var engine = Engine.Instances[engineIndex];
  10865. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10866. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10867. }
  10868. }
  10869. };
  10870. Object.defineProperty(Engine, "NEVER", {
  10871. get: function () {
  10872. return Engine._NEVER;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Engine, "ALWAYS", {
  10878. get: function () {
  10879. return Engine._ALWAYS;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Engine, "LESS", {
  10885. get: function () {
  10886. return Engine._LESS;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Engine, "EQUAL", {
  10892. get: function () {
  10893. return Engine._EQUAL;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Engine, "LEQUAL", {
  10899. get: function () {
  10900. return Engine._LEQUAL;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Engine, "GREATER", {
  10906. get: function () {
  10907. return Engine._GREATER;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "GEQUAL", {
  10913. get: function () {
  10914. return Engine._GEQUAL;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Engine, "NOTEQUAL", {
  10920. get: function () {
  10921. return Engine._NOTEQUAL;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Engine, "KEEP", {
  10927. get: function () {
  10928. return Engine._KEEP;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Engine, "REPLACE", {
  10934. get: function () {
  10935. return Engine._REPLACE;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Engine, "INCR", {
  10941. get: function () {
  10942. return Engine._INCR;
  10943. },
  10944. enumerable: true,
  10945. configurable: true
  10946. });
  10947. Object.defineProperty(Engine, "DECR", {
  10948. get: function () {
  10949. return Engine._DECR;
  10950. },
  10951. enumerable: true,
  10952. configurable: true
  10953. });
  10954. Object.defineProperty(Engine, "INVERT", {
  10955. get: function () {
  10956. return Engine._INVERT;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. Object.defineProperty(Engine, "INCR_WRAP", {
  10962. get: function () {
  10963. return Engine._INCR_WRAP;
  10964. },
  10965. enumerable: true,
  10966. configurable: true
  10967. });
  10968. Object.defineProperty(Engine, "DECR_WRAP", {
  10969. get: function () {
  10970. return Engine._DECR_WRAP;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10976. get: function () {
  10977. return Engine._ALPHA_DISABLE;
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10983. get: function () {
  10984. return Engine._ALPHA_ONEONE;
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Engine, "ALPHA_ADD", {
  10990. get: function () {
  10991. return Engine._ALPHA_ADD;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10997. get: function () {
  10998. return Engine._ALPHA_COMBINE;
  10999. },
  11000. enumerable: true,
  11001. configurable: true
  11002. });
  11003. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11004. get: function () {
  11005. return Engine._ALPHA_SUBTRACT;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11011. get: function () {
  11012. return Engine._ALPHA_MULTIPLY;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11018. get: function () {
  11019. return Engine._ALPHA_MAXIMIZED;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11025. get: function () {
  11026. return Engine._ALPHA_PREMULTIPLIED;
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11032. get: function () {
  11033. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11039. get: function () {
  11040. return Engine._ALPHA_INTERPOLATE;
  11041. },
  11042. enumerable: true,
  11043. configurable: true
  11044. });
  11045. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11046. get: function () {
  11047. return Engine._ALPHA_SCREENMODE;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11053. get: function () {
  11054. return Engine._DELAYLOADSTATE_NONE;
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11060. get: function () {
  11061. return Engine._DELAYLOADSTATE_LOADED;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11067. get: function () {
  11068. return Engine._DELAYLOADSTATE_LOADING;
  11069. },
  11070. enumerable: true,
  11071. configurable: true
  11072. });
  11073. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11074. get: function () {
  11075. return Engine._DELAYLOADSTATE_NOTLOADED;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11081. get: function () {
  11082. return Engine._TEXTUREFORMAT_ALPHA;
  11083. },
  11084. enumerable: true,
  11085. configurable: true
  11086. });
  11087. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11088. get: function () {
  11089. return Engine._TEXTUREFORMAT_LUMINANCE;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11095. /**
  11096. * R32F
  11097. */
  11098. get: function () {
  11099. return Engine._TEXTUREFORMAT_R32F;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11105. /**
  11106. * RG32F
  11107. */
  11108. get: function () {
  11109. return Engine._TEXTUREFORMAT_RG32F;
  11110. },
  11111. enumerable: true,
  11112. configurable: true
  11113. });
  11114. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11115. /**
  11116. * RGB32F
  11117. */
  11118. get: function () {
  11119. return Engine._TEXTUREFORMAT_RGB32F;
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11125. /**
  11126. * RGBA32F
  11127. */
  11128. get: function () {
  11129. return Engine._TEXTUREFORMAT_RGBA32F;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11135. get: function () {
  11136. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11142. get: function () {
  11143. return Engine._TEXTUREFORMAT_RGB;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11149. get: function () {
  11150. return Engine._TEXTUREFORMAT_RGBA;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11156. get: function () {
  11157. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11163. get: function () {
  11164. return Engine._TEXTURETYPE_FLOAT;
  11165. },
  11166. enumerable: true,
  11167. configurable: true
  11168. });
  11169. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11170. get: function () {
  11171. return Engine._TEXTURETYPE_HALF_FLOAT;
  11172. },
  11173. enumerable: true,
  11174. configurable: true
  11175. });
  11176. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11177. get: function () {
  11178. return Engine._SCALEMODE_FLOOR;
  11179. },
  11180. enumerable: true,
  11181. configurable: true
  11182. });
  11183. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11184. get: function () {
  11185. return Engine._SCALEMODE_NEAREST;
  11186. },
  11187. enumerable: true,
  11188. configurable: true
  11189. });
  11190. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11191. get: function () {
  11192. return Engine._SCALEMODE_CEILING;
  11193. },
  11194. enumerable: true,
  11195. configurable: true
  11196. });
  11197. Object.defineProperty(Engine, "Version", {
  11198. get: function () {
  11199. return "3.2.0-beta.2";
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11205. get: function () {
  11206. return this._vrExclusivePointerMode;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11212. get: function () {
  11213. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11214. },
  11215. enumerable: true,
  11216. configurable: true
  11217. });
  11218. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11219. get: function () {
  11220. return this._webGLVersion < 2 || this.forcePOTTextures;
  11221. },
  11222. enumerable: true,
  11223. configurable: true
  11224. });
  11225. Object.defineProperty(Engine.prototype, "badOS", {
  11226. get: function () {
  11227. return this._badOS;
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11233. get: function () {
  11234. return this._badDesktopOS;
  11235. },
  11236. enumerable: true,
  11237. configurable: true
  11238. });
  11239. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11240. get: function () {
  11241. return this._performanceMonitor;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11247. get: function () {
  11248. return this._texturesSupported;
  11249. },
  11250. enumerable: true,
  11251. configurable: true
  11252. });
  11253. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11254. get: function () {
  11255. return this._textureFormatInUse;
  11256. },
  11257. enumerable: true,
  11258. configurable: true
  11259. });
  11260. Object.defineProperty(Engine.prototype, "currentViewport", {
  11261. get: function () {
  11262. return this._cachedViewport;
  11263. },
  11264. enumerable: true,
  11265. configurable: true
  11266. });
  11267. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11268. // Empty texture
  11269. get: function () {
  11270. if (!this._emptyTexture) {
  11271. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11272. }
  11273. return this._emptyTexture;
  11274. },
  11275. enumerable: true,
  11276. configurable: true
  11277. });
  11278. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11279. get: function () {
  11280. if (!this._emptyTexture3D) {
  11281. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11282. }
  11283. return this._emptyTexture3D;
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11289. get: function () {
  11290. if (!this._emptyCubeTexture) {
  11291. var faceData = new Uint8Array(4);
  11292. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11293. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11294. }
  11295. return this._emptyCubeTexture;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Engine.prototype._rebuildInternalTextures = function () {
  11301. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11302. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11303. var internalTexture = currentState_1[_i];
  11304. internalTexture._rebuild();
  11305. }
  11306. };
  11307. Engine.prototype._rebuildEffects = function () {
  11308. for (var key in this._compiledEffects) {
  11309. var effect = this._compiledEffects[key];
  11310. effect._prepareEffect();
  11311. }
  11312. BABYLON.Effect.ResetCache();
  11313. };
  11314. Engine.prototype._rebuildBuffers = function () {
  11315. // Index / Vertex
  11316. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11317. var scene = _a[_i];
  11318. scene.resetCachedMaterial();
  11319. scene._rebuildGeometries();
  11320. scene._rebuildTextures();
  11321. }
  11322. // Uniforms
  11323. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11324. var uniformBuffer = _c[_b];
  11325. uniformBuffer._rebuild();
  11326. }
  11327. };
  11328. Engine.prototype._initGLContext = function () {
  11329. // Caps
  11330. this._caps = new EngineCapabilities();
  11331. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11332. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11333. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11334. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11335. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11336. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11337. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11338. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11339. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11340. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11341. // Infos
  11342. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11343. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11344. if (rendererInfo != null) {
  11345. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11346. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11347. }
  11348. if (!this._glVendor) {
  11349. this._glVendor = "Unknown vendor";
  11350. }
  11351. if (!this._glRenderer) {
  11352. this._glRenderer = "Unknown renderer";
  11353. }
  11354. // Constants
  11355. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11356. if (this._gl.RGBA16F !== 0x881A) {
  11357. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11358. }
  11359. if (this._gl.RGBA32F !== 0x8814) {
  11360. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11361. }
  11362. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11363. this._gl.DEPTH24_STENCIL8 = 35056;
  11364. }
  11365. // Extensions
  11366. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11367. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11368. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11369. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11370. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11371. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11372. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11373. 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');
  11374. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11375. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11376. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11377. this._caps.highPrecisionShaderSupported = true;
  11378. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11379. if (this._caps.timerQuery) {
  11380. if (this._webGLVersion === 1) {
  11381. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11382. }
  11383. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11384. }
  11385. // Checks if some of the format renders first to allow the use of webgl inspector.
  11386. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11387. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11388. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11389. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11390. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11391. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11392. if (this._webGLVersion > 1) {
  11393. this._gl.HALF_FLOAT_OES = 0x140B;
  11394. }
  11395. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11396. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11397. // Draw buffers
  11398. if (this._webGLVersion > 1) {
  11399. this._caps.drawBuffersExtension = true;
  11400. }
  11401. else {
  11402. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11403. if (drawBuffersExtension !== null) {
  11404. this._caps.drawBuffersExtension = true;
  11405. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11406. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11407. for (var i = 0; i < 16; i++) {
  11408. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11409. }
  11410. }
  11411. else {
  11412. this._caps.drawBuffersExtension = false;
  11413. }
  11414. }
  11415. // Depth Texture
  11416. if (this._webGLVersion > 1) {
  11417. this._caps.depthTextureExtension = true;
  11418. }
  11419. else {
  11420. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11421. if (depthTextureExtension != null) {
  11422. this._caps.depthTextureExtension = true;
  11423. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11424. }
  11425. }
  11426. // Vertex array object
  11427. if (this._webGLVersion > 1) {
  11428. this._caps.vertexArrayObject = true;
  11429. }
  11430. else {
  11431. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11432. if (vertexArrayObjectExtension != null) {
  11433. this._caps.vertexArrayObject = true;
  11434. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11435. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11436. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11437. }
  11438. else {
  11439. this._caps.vertexArrayObject = false;
  11440. }
  11441. }
  11442. // Instances count
  11443. if (this._webGLVersion > 1) {
  11444. this._caps.instancedArrays = true;
  11445. }
  11446. else {
  11447. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11448. if (instanceExtension != null) {
  11449. this._caps.instancedArrays = true;
  11450. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11451. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11452. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11453. }
  11454. else {
  11455. this._caps.instancedArrays = false;
  11456. }
  11457. }
  11458. // Intelligently add supported compressed formats in order to check for.
  11459. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11460. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11461. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11462. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11463. if (this._caps.astc)
  11464. this.texturesSupported.push('-astc.ktx');
  11465. if (this._caps.s3tc)
  11466. this.texturesSupported.push('-dxt.ktx');
  11467. if (this._caps.pvrtc)
  11468. this.texturesSupported.push('-pvrtc.ktx');
  11469. if (this._caps.etc2)
  11470. this.texturesSupported.push('-etc2.ktx');
  11471. if (this._caps.etc1)
  11472. this.texturesSupported.push('-etc1.ktx');
  11473. if (this._gl.getShaderPrecisionFormat) {
  11474. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11475. if (highp) {
  11476. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11477. }
  11478. }
  11479. // Depth buffer
  11480. this.setDepthBuffer(true);
  11481. this.setDepthFunctionToLessOrEqual();
  11482. this.setDepthWrite(true);
  11483. // Texture maps
  11484. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11485. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11486. this._nextFreeTextureSlots.push(slot);
  11487. }
  11488. };
  11489. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11490. get: function () {
  11491. return this._webGLVersion;
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11497. /**
  11498. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11499. */
  11500. get: function () {
  11501. return this._isStencilEnable;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Engine.prototype._prepareWorkingCanvas = function () {
  11507. if (this._workingCanvas) {
  11508. return;
  11509. }
  11510. this._workingCanvas = document.createElement("canvas");
  11511. var context = this._workingCanvas.getContext("2d");
  11512. if (context) {
  11513. this._workingContext = context;
  11514. }
  11515. };
  11516. Engine.prototype.resetTextureCache = function () {
  11517. for (var key in this._boundTexturesCache) {
  11518. var boundTexture = this._boundTexturesCache[key];
  11519. if (boundTexture) {
  11520. this._removeDesignatedSlot(boundTexture);
  11521. }
  11522. this._boundTexturesCache[key] = null;
  11523. }
  11524. if (!this.disableTextureBindingOptimization) {
  11525. this._nextFreeTextureSlots = [];
  11526. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11527. this._nextFreeTextureSlots.push(slot);
  11528. }
  11529. }
  11530. this._currentTextureChannel = -1;
  11531. };
  11532. Engine.prototype.isDeterministicLockStep = function () {
  11533. return this._deterministicLockstep;
  11534. };
  11535. Engine.prototype.getLockstepMaxSteps = function () {
  11536. return this._lockstepMaxSteps;
  11537. };
  11538. Engine.prototype.getGlInfo = function () {
  11539. return {
  11540. vendor: this._glVendor,
  11541. renderer: this._glRenderer,
  11542. version: this._glVersion
  11543. };
  11544. };
  11545. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11546. if (useScreen === void 0) { useScreen = false; }
  11547. var viewport = camera.viewport;
  11548. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11549. };
  11550. Engine.prototype.getRenderWidth = function (useScreen) {
  11551. if (useScreen === void 0) { useScreen = false; }
  11552. if (!useScreen && this._currentRenderTarget) {
  11553. return this._currentRenderTarget.width;
  11554. }
  11555. return this._gl.drawingBufferWidth;
  11556. };
  11557. Engine.prototype.getRenderHeight = function (useScreen) {
  11558. if (useScreen === void 0) { useScreen = false; }
  11559. if (!useScreen && this._currentRenderTarget) {
  11560. return this._currentRenderTarget.height;
  11561. }
  11562. return this._gl.drawingBufferHeight;
  11563. };
  11564. Engine.prototype.getRenderingCanvas = function () {
  11565. return this._renderingCanvas;
  11566. };
  11567. Engine.prototype.getRenderingCanvasClientRect = function () {
  11568. if (!this._renderingCanvas) {
  11569. return null;
  11570. }
  11571. return this._renderingCanvas.getBoundingClientRect();
  11572. };
  11573. Engine.prototype.setHardwareScalingLevel = function (level) {
  11574. this._hardwareScalingLevel = level;
  11575. this.resize();
  11576. };
  11577. Engine.prototype.getHardwareScalingLevel = function () {
  11578. return this._hardwareScalingLevel;
  11579. };
  11580. Engine.prototype.getLoadedTexturesCache = function () {
  11581. return this._internalTexturesCache;
  11582. };
  11583. Engine.prototype.getCaps = function () {
  11584. return this._caps;
  11585. };
  11586. Object.defineProperty(Engine.prototype, "drawCalls", {
  11587. /** The number of draw calls submitted last frame */
  11588. get: function () {
  11589. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11590. return 0;
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11596. get: function () {
  11597. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11598. return null;
  11599. },
  11600. enumerable: true,
  11601. configurable: true
  11602. });
  11603. Engine.prototype.getDepthFunction = function () {
  11604. return this._depthCullingState.depthFunc;
  11605. };
  11606. Engine.prototype.setDepthFunction = function (depthFunc) {
  11607. this._depthCullingState.depthFunc = depthFunc;
  11608. };
  11609. Engine.prototype.setDepthFunctionToGreater = function () {
  11610. this._depthCullingState.depthFunc = this._gl.GREATER;
  11611. };
  11612. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11613. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11614. };
  11615. Engine.prototype.setDepthFunctionToLess = function () {
  11616. this._depthCullingState.depthFunc = this._gl.LESS;
  11617. };
  11618. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11619. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11620. };
  11621. Engine.prototype.getStencilBuffer = function () {
  11622. return this._stencilState.stencilTest;
  11623. };
  11624. Engine.prototype.setStencilBuffer = function (enable) {
  11625. this._stencilState.stencilTest = enable;
  11626. };
  11627. Engine.prototype.getStencilMask = function () {
  11628. return this._stencilState.stencilMask;
  11629. };
  11630. Engine.prototype.setStencilMask = function (mask) {
  11631. this._stencilState.stencilMask = mask;
  11632. };
  11633. Engine.prototype.getStencilFunction = function () {
  11634. return this._stencilState.stencilFunc;
  11635. };
  11636. Engine.prototype.getStencilFunctionReference = function () {
  11637. return this._stencilState.stencilFuncRef;
  11638. };
  11639. Engine.prototype.getStencilFunctionMask = function () {
  11640. return this._stencilState.stencilFuncMask;
  11641. };
  11642. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11643. this._stencilState.stencilFunc = stencilFunc;
  11644. };
  11645. Engine.prototype.setStencilFunctionReference = function (reference) {
  11646. this._stencilState.stencilFuncRef = reference;
  11647. };
  11648. Engine.prototype.setStencilFunctionMask = function (mask) {
  11649. this._stencilState.stencilFuncMask = mask;
  11650. };
  11651. Engine.prototype.getStencilOperationFail = function () {
  11652. return this._stencilState.stencilOpStencilFail;
  11653. };
  11654. Engine.prototype.getStencilOperationDepthFail = function () {
  11655. return this._stencilState.stencilOpDepthFail;
  11656. };
  11657. Engine.prototype.getStencilOperationPass = function () {
  11658. return this._stencilState.stencilOpStencilDepthPass;
  11659. };
  11660. Engine.prototype.setStencilOperationFail = function (operation) {
  11661. this._stencilState.stencilOpStencilFail = operation;
  11662. };
  11663. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11664. this._stencilState.stencilOpDepthFail = operation;
  11665. };
  11666. Engine.prototype.setStencilOperationPass = function (operation) {
  11667. this._stencilState.stencilOpStencilDepthPass = operation;
  11668. };
  11669. Engine.prototype.setDitheringState = function (value) {
  11670. if (value) {
  11671. this._gl.enable(this._gl.DITHER);
  11672. }
  11673. else {
  11674. this._gl.disable(this._gl.DITHER);
  11675. }
  11676. };
  11677. Engine.prototype.setRasterizerState = function (value) {
  11678. if (value) {
  11679. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11680. }
  11681. else {
  11682. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11683. }
  11684. };
  11685. /**
  11686. * stop executing a render loop function and remove it from the execution array
  11687. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11688. */
  11689. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11690. if (!renderFunction) {
  11691. this._activeRenderLoops = [];
  11692. return;
  11693. }
  11694. var index = this._activeRenderLoops.indexOf(renderFunction);
  11695. if (index >= 0) {
  11696. this._activeRenderLoops.splice(index, 1);
  11697. }
  11698. };
  11699. Engine.prototype._renderLoop = function () {
  11700. if (!this._contextWasLost) {
  11701. var shouldRender = true;
  11702. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11703. shouldRender = false;
  11704. }
  11705. if (shouldRender) {
  11706. // Start new frame
  11707. this.beginFrame();
  11708. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11709. var renderFunction = this._activeRenderLoops[index];
  11710. renderFunction();
  11711. }
  11712. // Present
  11713. this.endFrame();
  11714. }
  11715. }
  11716. if (this._activeRenderLoops.length > 0) {
  11717. // Register new frame
  11718. var requester = null;
  11719. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11720. requester = this._vrDisplay;
  11721. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11722. }
  11723. else {
  11724. this._renderingQueueLaunched = false;
  11725. }
  11726. };
  11727. /**
  11728. * Register and execute a render loop. The engine can have more than one render function.
  11729. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11730. * @example
  11731. * engine.runRenderLoop(function () {
  11732. * scene.render()
  11733. * })
  11734. */
  11735. Engine.prototype.runRenderLoop = function (renderFunction) {
  11736. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11737. return;
  11738. }
  11739. this._activeRenderLoops.push(renderFunction);
  11740. if (!this._renderingQueueLaunched) {
  11741. this._renderingQueueLaunched = true;
  11742. this._bindedRenderFunction = this._renderLoop.bind(this);
  11743. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11744. }
  11745. };
  11746. /**
  11747. * Toggle full screen mode.
  11748. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11749. * @param {any} options - an options object to be sent to the requestFullscreen function
  11750. */
  11751. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11752. if (this.isFullscreen) {
  11753. BABYLON.Tools.ExitFullscreen();
  11754. }
  11755. else {
  11756. this._pointerLockRequested = requestPointerLock;
  11757. if (this._renderingCanvas) {
  11758. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11759. }
  11760. }
  11761. };
  11762. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11763. if (stencil === void 0) { stencil = false; }
  11764. this.applyStates();
  11765. var mode = 0;
  11766. if (backBuffer && color) {
  11767. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11768. mode |= this._gl.COLOR_BUFFER_BIT;
  11769. }
  11770. if (depth) {
  11771. this._gl.clearDepth(1.0);
  11772. mode |= this._gl.DEPTH_BUFFER_BIT;
  11773. }
  11774. if (stencil) {
  11775. this._gl.clearStencil(0);
  11776. mode |= this._gl.STENCIL_BUFFER_BIT;
  11777. }
  11778. this._gl.clear(mode);
  11779. };
  11780. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11781. var gl = this._gl;
  11782. // Save state
  11783. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11784. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11785. // Change state
  11786. gl.enable(gl.SCISSOR_TEST);
  11787. gl.scissor(x, y, width, height);
  11788. // Clear
  11789. this.clear(clearColor, true, true, true);
  11790. // Restore state
  11791. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11792. if (curScissor === true) {
  11793. gl.enable(gl.SCISSOR_TEST);
  11794. }
  11795. else {
  11796. gl.disable(gl.SCISSOR_TEST);
  11797. }
  11798. };
  11799. /**
  11800. * Set the WebGL's viewport
  11801. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11802. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11803. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11804. */
  11805. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11806. var width = requiredWidth || this.getRenderWidth();
  11807. var height = requiredHeight || this.getRenderHeight();
  11808. var x = viewport.x || 0;
  11809. var y = viewport.y || 0;
  11810. this._cachedViewport = viewport;
  11811. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11812. };
  11813. /**
  11814. * Directly set the WebGL Viewport
  11815. * The x, y, width & height are directly passed to the WebGL call
  11816. * @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.
  11817. */
  11818. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11819. var currentViewport = this._cachedViewport;
  11820. this._cachedViewport = null;
  11821. this._gl.viewport(x, y, width, height);
  11822. return currentViewport;
  11823. };
  11824. Engine.prototype.beginFrame = function () {
  11825. this.onBeginFrameObservable.notifyObservers(this);
  11826. this._measureFps();
  11827. };
  11828. Engine.prototype.endFrame = function () {
  11829. //force a flush in case we are using a bad OS.
  11830. if (this._badOS) {
  11831. this.flushFramebuffer();
  11832. }
  11833. //submit frame to the vr device, if enabled
  11834. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11835. // TODO: We should only submit the frame if we read frameData successfully.
  11836. this._vrDisplay.submitFrame();
  11837. }
  11838. this.onEndFrameObservable.notifyObservers(this);
  11839. };
  11840. /**
  11841. * resize the view according to the canvas' size.
  11842. * @example
  11843. * window.addEventListener("resize", function () {
  11844. * engine.resize();
  11845. * });
  11846. */
  11847. Engine.prototype.resize = function () {
  11848. // We're not resizing the size of the canvas while in VR mode & presenting
  11849. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11850. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11851. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11852. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11853. }
  11854. };
  11855. /**
  11856. * force a specific size of the canvas
  11857. * @param {number} width - the new canvas' width
  11858. * @param {number} height - the new canvas' height
  11859. */
  11860. Engine.prototype.setSize = function (width, height) {
  11861. if (!this._renderingCanvas) {
  11862. return;
  11863. }
  11864. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11865. return;
  11866. }
  11867. this._renderingCanvas.width = width;
  11868. this._renderingCanvas.height = height;
  11869. for (var index = 0; index < this.scenes.length; index++) {
  11870. var scene = this.scenes[index];
  11871. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11872. var cam = scene.cameras[camIndex];
  11873. cam._currentRenderId = 0;
  11874. }
  11875. }
  11876. if (this.onResizeObservable.hasObservers) {
  11877. this.onResizeObservable.notifyObservers(this);
  11878. }
  11879. };
  11880. // WebVR functions
  11881. Engine.prototype.isVRDevicePresent = function () {
  11882. return !!this._vrDisplay;
  11883. };
  11884. Engine.prototype.getVRDevice = function () {
  11885. return this._vrDisplay;
  11886. };
  11887. /**
  11888. * Initializes a webVR display and starts listening to display change events.
  11889. * The onVRDisplayChangedObservable will be notified upon these changes.
  11890. * @returns The onVRDisplayChangedObservable.
  11891. */
  11892. Engine.prototype.initWebVR = function () {
  11893. this.initWebVRAsync();
  11894. return this.onVRDisplayChangedObservable;
  11895. };
  11896. /**
  11897. * Initializes a webVR display and starts listening to display change events.
  11898. * The onVRDisplayChangedObservable will be notified upon these changes.
  11899. * @returns A promise containing a VRDisplay and if vr is supported.
  11900. */
  11901. Engine.prototype.initWebVRAsync = function () {
  11902. var _this = this;
  11903. var notifyObservers = function () {
  11904. var eventArgs = {
  11905. vrDisplay: _this._vrDisplay,
  11906. vrSupported: _this._vrSupported
  11907. };
  11908. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11909. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11910. };
  11911. if (!this._onVrDisplayConnect) {
  11912. this._onVrDisplayConnect = function (event) {
  11913. _this._vrDisplay = event.display;
  11914. notifyObservers();
  11915. };
  11916. this._onVrDisplayDisconnect = function () {
  11917. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11918. _this._vrDisplay = undefined;
  11919. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11920. notifyObservers();
  11921. };
  11922. this._onVrDisplayPresentChange = function () {
  11923. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11924. };
  11925. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11926. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11927. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11928. }
  11929. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11930. this._webVRInitPromise.then(notifyObservers);
  11931. return this._webVRInitPromise;
  11932. };
  11933. Engine.prototype.enableVR = function () {
  11934. var _this = this;
  11935. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11936. var onResolved = function () {
  11937. _this.onVRRequestPresentComplete.notifyObservers(true);
  11938. _this._onVRFullScreenTriggered();
  11939. };
  11940. var onRejected = function () {
  11941. _this.onVRRequestPresentComplete.notifyObservers(false);
  11942. };
  11943. this.onVRRequestPresentStart.notifyObservers(this);
  11944. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11945. }
  11946. };
  11947. Engine.prototype.disableVR = function () {
  11948. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11949. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11950. }
  11951. };
  11952. Engine.prototype._getVRDisplaysAsync = function () {
  11953. var _this = this;
  11954. return new Promise(function (res, rej) {
  11955. if (navigator.getVRDisplays) {
  11956. navigator.getVRDisplays().then(function (devices) {
  11957. _this._vrSupported = true;
  11958. // note that devices may actually be an empty array. This is fine;
  11959. // we expect this._vrDisplay to be undefined in this case.
  11960. _this._vrDisplay = devices[0];
  11961. res({
  11962. vrDisplay: _this._vrDisplay,
  11963. vrSupported: _this._vrSupported
  11964. });
  11965. });
  11966. }
  11967. else {
  11968. _this._vrDisplay = undefined;
  11969. _this._vrSupported = false;
  11970. res({
  11971. vrDisplay: _this._vrDisplay,
  11972. vrSupported: _this._vrSupported
  11973. });
  11974. }
  11975. });
  11976. };
  11977. /**
  11978. * Binds the frame buffer to the specified texture.
  11979. * @param texture The texture to render to or null for the default canvas
  11980. * @param faceIndex The face of the texture to render to in case of cube texture
  11981. * @param requiredWidth The width of the target to render to
  11982. * @param requiredHeight The height of the target to render to
  11983. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  11984. * @param depthStencilTexture The depth stencil texture to use to render
  11985. */
  11986. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  11987. if (this._currentRenderTarget) {
  11988. this.unBindFramebuffer(this._currentRenderTarget);
  11989. }
  11990. this._currentRenderTarget = texture;
  11991. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11992. var gl = this._gl;
  11993. if (texture.isCube) {
  11994. if (faceIndex === undefined) {
  11995. faceIndex = 0;
  11996. }
  11997. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11998. if (depthStencilTexture) {
  11999. if (depthStencilTexture._generateStencilBuffer) {
  12000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12001. }
  12002. else {
  12003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12004. }
  12005. }
  12006. }
  12007. if (this._cachedViewport && !forceFullscreenViewport) {
  12008. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12009. }
  12010. else {
  12011. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12012. }
  12013. this.wipeCaches();
  12014. };
  12015. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12016. if (this._currentFramebuffer !== framebuffer) {
  12017. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12018. this._currentFramebuffer = framebuffer;
  12019. }
  12020. };
  12021. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12022. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12023. this._currentRenderTarget = null;
  12024. // If MSAA, we need to bitblt back to main texture
  12025. var gl = this._gl;
  12026. if (texture._MSAAFramebuffer) {
  12027. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12028. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12029. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12030. }
  12031. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12032. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12033. gl.generateMipmap(gl.TEXTURE_2D);
  12034. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12035. }
  12036. if (onBeforeUnbind) {
  12037. if (texture._MSAAFramebuffer) {
  12038. // Bind the correct framebuffer
  12039. this.bindUnboundFramebuffer(texture._framebuffer);
  12040. }
  12041. onBeforeUnbind();
  12042. }
  12043. this.bindUnboundFramebuffer(null);
  12044. };
  12045. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12046. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12047. this._currentRenderTarget = null;
  12048. // If MSAA, we need to bitblt back to main texture
  12049. var gl = this._gl;
  12050. if (textures[0]._MSAAFramebuffer) {
  12051. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12052. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12053. var attachments = textures[0]._attachments;
  12054. if (!attachments) {
  12055. attachments = new Array(textures.length);
  12056. textures[0]._attachments = attachments;
  12057. }
  12058. for (var i = 0; i < textures.length; i++) {
  12059. var texture = textures[i];
  12060. for (var j = 0; j < attachments.length; j++) {
  12061. attachments[j] = gl.NONE;
  12062. }
  12063. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12064. gl.readBuffer(attachments[i]);
  12065. gl.drawBuffers(attachments);
  12066. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12067. }
  12068. for (var i = 0; i < attachments.length; i++) {
  12069. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12070. }
  12071. gl.drawBuffers(attachments);
  12072. }
  12073. for (var i = 0; i < textures.length; i++) {
  12074. var texture = textures[i];
  12075. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12076. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12077. gl.generateMipmap(gl.TEXTURE_2D);
  12078. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12079. }
  12080. }
  12081. if (onBeforeUnbind) {
  12082. if (textures[0]._MSAAFramebuffer) {
  12083. // Bind the correct framebuffer
  12084. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12085. }
  12086. onBeforeUnbind();
  12087. }
  12088. this.bindUnboundFramebuffer(null);
  12089. };
  12090. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12091. if (texture.generateMipMaps) {
  12092. var gl = this._gl;
  12093. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12094. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12095. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12096. }
  12097. };
  12098. Engine.prototype.flushFramebuffer = function () {
  12099. this._gl.flush();
  12100. };
  12101. Engine.prototype.restoreDefaultFramebuffer = function () {
  12102. if (this._currentRenderTarget) {
  12103. this.unBindFramebuffer(this._currentRenderTarget);
  12104. }
  12105. else {
  12106. this.bindUnboundFramebuffer(null);
  12107. }
  12108. if (this._cachedViewport) {
  12109. this.setViewport(this._cachedViewport);
  12110. }
  12111. this.wipeCaches();
  12112. };
  12113. // UBOs
  12114. Engine.prototype.createUniformBuffer = function (elements) {
  12115. var ubo = this._gl.createBuffer();
  12116. if (!ubo) {
  12117. throw new Error("Unable to create uniform buffer");
  12118. }
  12119. this.bindUniformBuffer(ubo);
  12120. if (elements instanceof Float32Array) {
  12121. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12122. }
  12123. else {
  12124. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12125. }
  12126. this.bindUniformBuffer(null);
  12127. ubo.references = 1;
  12128. return ubo;
  12129. };
  12130. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12131. var ubo = this._gl.createBuffer();
  12132. if (!ubo) {
  12133. throw new Error("Unable to create dynamic uniform buffer");
  12134. }
  12135. this.bindUniformBuffer(ubo);
  12136. if (elements instanceof Float32Array) {
  12137. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12138. }
  12139. else {
  12140. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12141. }
  12142. this.bindUniformBuffer(null);
  12143. ubo.references = 1;
  12144. return ubo;
  12145. };
  12146. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12147. this.bindUniformBuffer(uniformBuffer);
  12148. if (offset === undefined) {
  12149. offset = 0;
  12150. }
  12151. if (count === undefined) {
  12152. if (elements instanceof Float32Array) {
  12153. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12154. }
  12155. else {
  12156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12157. }
  12158. }
  12159. else {
  12160. if (elements instanceof Float32Array) {
  12161. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12162. }
  12163. else {
  12164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12165. }
  12166. }
  12167. this.bindUniformBuffer(null);
  12168. };
  12169. // VBOs
  12170. Engine.prototype._resetVertexBufferBinding = function () {
  12171. this.bindArrayBuffer(null);
  12172. this._cachedVertexBuffers = null;
  12173. };
  12174. Engine.prototype.createVertexBuffer = function (vertices) {
  12175. var vbo = this._gl.createBuffer();
  12176. if (!vbo) {
  12177. throw new Error("Unable to create vertex buffer");
  12178. }
  12179. this.bindArrayBuffer(vbo);
  12180. if (vertices instanceof Float32Array) {
  12181. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12182. }
  12183. else {
  12184. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12185. }
  12186. this._resetVertexBufferBinding();
  12187. vbo.references = 1;
  12188. return vbo;
  12189. };
  12190. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12191. var vbo = this._gl.createBuffer();
  12192. if (!vbo) {
  12193. throw new Error("Unable to create dynamic vertex buffer");
  12194. }
  12195. this.bindArrayBuffer(vbo);
  12196. if (vertices instanceof Float32Array) {
  12197. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12198. }
  12199. else {
  12200. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12201. }
  12202. this._resetVertexBufferBinding();
  12203. vbo.references = 1;
  12204. return vbo;
  12205. };
  12206. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12207. if (offset === void 0) { offset = 0; }
  12208. // Force cache update
  12209. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12210. this.bindIndexBuffer(indexBuffer);
  12211. var arrayBuffer;
  12212. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12213. arrayBuffer = indices;
  12214. }
  12215. else {
  12216. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12217. }
  12218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12219. this._resetIndexBufferBinding();
  12220. };
  12221. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12222. this.bindArrayBuffer(vertexBuffer);
  12223. if (offset === undefined) {
  12224. offset = 0;
  12225. }
  12226. if (count === undefined) {
  12227. if (vertices instanceof Float32Array) {
  12228. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12229. }
  12230. else {
  12231. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12232. }
  12233. }
  12234. else {
  12235. if (vertices instanceof Float32Array) {
  12236. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12237. }
  12238. else {
  12239. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12240. }
  12241. }
  12242. this._resetVertexBufferBinding();
  12243. };
  12244. Engine.prototype._resetIndexBufferBinding = function () {
  12245. this.bindIndexBuffer(null);
  12246. this._cachedIndexBuffer = null;
  12247. };
  12248. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12249. var vbo = this._gl.createBuffer();
  12250. if (!vbo) {
  12251. throw new Error("Unable to create index buffer");
  12252. }
  12253. this.bindIndexBuffer(vbo);
  12254. // Check for 32 bits indices
  12255. var arrayBuffer;
  12256. var need32Bits = false;
  12257. if (indices instanceof Uint16Array) {
  12258. arrayBuffer = indices;
  12259. }
  12260. else {
  12261. //check 32 bit support
  12262. if (this._caps.uintIndices) {
  12263. if (indices instanceof Uint32Array) {
  12264. arrayBuffer = indices;
  12265. need32Bits = true;
  12266. }
  12267. else {
  12268. //number[] or Int32Array, check if 32 bit is necessary
  12269. for (var index = 0; index < indices.length; index++) {
  12270. if (indices[index] > 65535) {
  12271. need32Bits = true;
  12272. break;
  12273. }
  12274. }
  12275. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12276. }
  12277. }
  12278. else {
  12279. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12280. arrayBuffer = new Uint16Array(indices);
  12281. }
  12282. }
  12283. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12284. this._resetIndexBufferBinding();
  12285. vbo.references = 1;
  12286. vbo.is32Bits = need32Bits;
  12287. return vbo;
  12288. };
  12289. Engine.prototype.bindArrayBuffer = function (buffer) {
  12290. if (!this._vaoRecordInProgress) {
  12291. this._unbindVertexArrayObject();
  12292. }
  12293. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12294. };
  12295. Engine.prototype.bindUniformBuffer = function (buffer) {
  12296. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12297. };
  12298. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12299. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12300. };
  12301. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12302. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12303. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12304. };
  12305. ;
  12306. Engine.prototype.bindIndexBuffer = function (buffer) {
  12307. if (!this._vaoRecordInProgress) {
  12308. this._unbindVertexArrayObject();
  12309. }
  12310. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12311. };
  12312. Engine.prototype.bindBuffer = function (buffer, target) {
  12313. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12314. this._gl.bindBuffer(target, buffer);
  12315. this._currentBoundBuffer[target] = buffer;
  12316. }
  12317. };
  12318. Engine.prototype.updateArrayBuffer = function (data) {
  12319. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12320. };
  12321. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12322. var pointer = this._currentBufferPointers[indx];
  12323. var changed = false;
  12324. if (!pointer.active) {
  12325. changed = true;
  12326. pointer.active = true;
  12327. pointer.index = indx;
  12328. pointer.size = size;
  12329. pointer.type = type;
  12330. pointer.normalized = normalized;
  12331. pointer.stride = stride;
  12332. pointer.offset = offset;
  12333. pointer.buffer = buffer;
  12334. }
  12335. else {
  12336. if (pointer.buffer !== buffer) {
  12337. pointer.buffer = buffer;
  12338. changed = true;
  12339. }
  12340. if (pointer.size !== size) {
  12341. pointer.size = size;
  12342. changed = true;
  12343. }
  12344. if (pointer.type !== type) {
  12345. pointer.type = type;
  12346. changed = true;
  12347. }
  12348. if (pointer.normalized !== normalized) {
  12349. pointer.normalized = normalized;
  12350. changed = true;
  12351. }
  12352. if (pointer.stride !== stride) {
  12353. pointer.stride = stride;
  12354. changed = true;
  12355. }
  12356. if (pointer.offset !== offset) {
  12357. pointer.offset = offset;
  12358. changed = true;
  12359. }
  12360. }
  12361. if (changed || this._vaoRecordInProgress) {
  12362. this.bindArrayBuffer(buffer);
  12363. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12364. }
  12365. };
  12366. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12367. if (indexBuffer == null) {
  12368. return;
  12369. }
  12370. if (this._cachedIndexBuffer !== indexBuffer) {
  12371. this._cachedIndexBuffer = indexBuffer;
  12372. this.bindIndexBuffer(indexBuffer);
  12373. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12374. }
  12375. };
  12376. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12377. var attributes = effect.getAttributesNames();
  12378. if (!this._vaoRecordInProgress) {
  12379. this._unbindVertexArrayObject();
  12380. }
  12381. this.unbindAllAttributes();
  12382. for (var index = 0; index < attributes.length; index++) {
  12383. var order = effect.getAttributeLocation(index);
  12384. if (order >= 0) {
  12385. var vertexBuffer = vertexBuffers[attributes[index]];
  12386. if (!vertexBuffer) {
  12387. continue;
  12388. }
  12389. this._gl.enableVertexAttribArray(order);
  12390. if (!this._vaoRecordInProgress) {
  12391. this._vertexAttribArraysEnabled[order] = true;
  12392. }
  12393. var buffer = vertexBuffer.getBuffer();
  12394. if (buffer) {
  12395. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12396. if (vertexBuffer.getIsInstanced()) {
  12397. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12398. if (!this._vaoRecordInProgress) {
  12399. this._currentInstanceLocations.push(order);
  12400. this._currentInstanceBuffers.push(buffer);
  12401. }
  12402. }
  12403. }
  12404. }
  12405. }
  12406. };
  12407. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12408. var vao = this._gl.createVertexArray();
  12409. this._vaoRecordInProgress = true;
  12410. this._gl.bindVertexArray(vao);
  12411. this._mustWipeVertexAttributes = true;
  12412. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12413. this.bindIndexBuffer(indexBuffer);
  12414. this._vaoRecordInProgress = false;
  12415. this._gl.bindVertexArray(null);
  12416. return vao;
  12417. };
  12418. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12419. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12420. this._cachedVertexArrayObject = vertexArrayObject;
  12421. this._gl.bindVertexArray(vertexArrayObject);
  12422. this._cachedVertexBuffers = null;
  12423. this._cachedIndexBuffer = null;
  12424. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12425. this._mustWipeVertexAttributes = true;
  12426. }
  12427. };
  12428. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12429. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12430. this._cachedVertexBuffers = vertexBuffer;
  12431. this._cachedEffectForVertexBuffers = effect;
  12432. var attributesCount = effect.getAttributesCount();
  12433. this._unbindVertexArrayObject();
  12434. this.unbindAllAttributes();
  12435. var offset = 0;
  12436. for (var index = 0; index < attributesCount; index++) {
  12437. if (index < vertexDeclaration.length) {
  12438. var order = effect.getAttributeLocation(index);
  12439. if (order >= 0) {
  12440. this._gl.enableVertexAttribArray(order);
  12441. this._vertexAttribArraysEnabled[order] = true;
  12442. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12443. }
  12444. offset += vertexDeclaration[index] * 4;
  12445. }
  12446. }
  12447. }
  12448. this._bindIndexBufferWithCache(indexBuffer);
  12449. };
  12450. Engine.prototype._unbindVertexArrayObject = function () {
  12451. if (!this._cachedVertexArrayObject) {
  12452. return;
  12453. }
  12454. this._cachedVertexArrayObject = null;
  12455. this._gl.bindVertexArray(null);
  12456. };
  12457. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12458. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12459. this._cachedVertexBuffers = vertexBuffers;
  12460. this._cachedEffectForVertexBuffers = effect;
  12461. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12462. }
  12463. this._bindIndexBufferWithCache(indexBuffer);
  12464. };
  12465. Engine.prototype.unbindInstanceAttributes = function () {
  12466. var boundBuffer;
  12467. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12468. var instancesBuffer = this._currentInstanceBuffers[i];
  12469. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12470. boundBuffer = instancesBuffer;
  12471. this.bindArrayBuffer(instancesBuffer);
  12472. }
  12473. var offsetLocation = this._currentInstanceLocations[i];
  12474. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12475. }
  12476. this._currentInstanceBuffers.length = 0;
  12477. this._currentInstanceLocations.length = 0;
  12478. };
  12479. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12480. this._gl.deleteVertexArray(vao);
  12481. };
  12482. Engine.prototype._releaseBuffer = function (buffer) {
  12483. buffer.references--;
  12484. if (buffer.references === 0) {
  12485. this._gl.deleteBuffer(buffer);
  12486. return true;
  12487. }
  12488. return false;
  12489. };
  12490. Engine.prototype.createInstancesBuffer = function (capacity) {
  12491. var buffer = this._gl.createBuffer();
  12492. if (!buffer) {
  12493. throw new Error("Unable to create instance buffer");
  12494. }
  12495. buffer.capacity = capacity;
  12496. this.bindArrayBuffer(buffer);
  12497. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12498. return buffer;
  12499. };
  12500. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12501. this._gl.deleteBuffer(buffer);
  12502. };
  12503. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12504. this.bindArrayBuffer(instancesBuffer);
  12505. if (data) {
  12506. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12507. }
  12508. if (offsetLocations[0].index !== undefined) {
  12509. var stride = 0;
  12510. for (var i = 0; i < offsetLocations.length; i++) {
  12511. var ai = offsetLocations[i];
  12512. stride += ai.attributeSize * 4;
  12513. }
  12514. for (var i = 0; i < offsetLocations.length; i++) {
  12515. var ai = offsetLocations[i];
  12516. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12517. this._gl.enableVertexAttribArray(ai.index);
  12518. this._vertexAttribArraysEnabled[ai.index] = true;
  12519. }
  12520. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12521. this._gl.vertexAttribDivisor(ai.index, 1);
  12522. this._currentInstanceLocations.push(ai.index);
  12523. this._currentInstanceBuffers.push(instancesBuffer);
  12524. }
  12525. }
  12526. else {
  12527. for (var index = 0; index < 4; index++) {
  12528. var offsetLocation = offsetLocations[index];
  12529. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12530. this._gl.enableVertexAttribArray(offsetLocation);
  12531. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12532. }
  12533. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12534. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12535. this._currentInstanceLocations.push(offsetLocation);
  12536. this._currentInstanceBuffers.push(instancesBuffer);
  12537. }
  12538. }
  12539. };
  12540. Engine.prototype.applyStates = function () {
  12541. this._depthCullingState.apply(this._gl);
  12542. this._stencilState.apply(this._gl);
  12543. this._alphaState.apply(this._gl);
  12544. };
  12545. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12546. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12547. };
  12548. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12549. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12550. };
  12551. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12552. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12553. };
  12554. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12555. // Apply states
  12556. this.applyStates();
  12557. this._drawCalls.addCount(1, false);
  12558. // Render
  12559. var drawMode = this._drawMode(fillMode);
  12560. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12561. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12562. if (instancesCount) {
  12563. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12564. }
  12565. else {
  12566. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12567. }
  12568. };
  12569. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12570. // Apply states
  12571. this.applyStates();
  12572. this._drawCalls.addCount(1, false);
  12573. var drawMode = this._drawMode(fillMode);
  12574. if (instancesCount) {
  12575. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12576. }
  12577. else {
  12578. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12579. }
  12580. };
  12581. Engine.prototype._drawMode = function (fillMode) {
  12582. switch (fillMode) {
  12583. // Triangle views
  12584. case BABYLON.Material.TriangleFillMode:
  12585. return this._gl.TRIANGLES;
  12586. case BABYLON.Material.PointFillMode:
  12587. return this._gl.POINTS;
  12588. case BABYLON.Material.WireFrameFillMode:
  12589. return this._gl.LINES;
  12590. // Draw modes
  12591. case BABYLON.Material.PointListDrawMode:
  12592. return this._gl.POINTS;
  12593. case BABYLON.Material.LineListDrawMode:
  12594. return this._gl.LINES;
  12595. case BABYLON.Material.LineLoopDrawMode:
  12596. return this._gl.LINE_LOOP;
  12597. case BABYLON.Material.LineStripDrawMode:
  12598. return this._gl.LINE_STRIP;
  12599. case BABYLON.Material.TriangleStripDrawMode:
  12600. return this._gl.TRIANGLE_STRIP;
  12601. case BABYLON.Material.TriangleFanDrawMode:
  12602. return this._gl.TRIANGLE_FAN;
  12603. default:
  12604. return this._gl.TRIANGLES;
  12605. }
  12606. };
  12607. // Shaders
  12608. Engine.prototype._releaseEffect = function (effect) {
  12609. if (this._compiledEffects[effect._key]) {
  12610. delete this._compiledEffects[effect._key];
  12611. this._deleteProgram(effect.getProgram());
  12612. }
  12613. };
  12614. Engine.prototype._deleteProgram = function (program) {
  12615. if (program) {
  12616. program.__SPECTOR_rebuildProgram = null;
  12617. if (program.transformFeedback) {
  12618. this.deleteTransformFeedback(program.transformFeedback);
  12619. program.transformFeedback = null;
  12620. }
  12621. this._gl.deleteProgram(program);
  12622. }
  12623. };
  12624. /**
  12625. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12626. * @param samplers An array of string used to represent textures
  12627. */
  12628. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12629. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12630. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12631. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12632. if (this._compiledEffects[name]) {
  12633. var compiledEffect = this._compiledEffects[name];
  12634. if (onCompiled && compiledEffect.isReady()) {
  12635. onCompiled(compiledEffect);
  12636. }
  12637. return compiledEffect;
  12638. }
  12639. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12640. effect._key = name;
  12641. this._compiledEffects[name] = effect;
  12642. return effect;
  12643. };
  12644. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12645. if (uniformsNames === void 0) { uniformsNames = []; }
  12646. if (samplers === void 0) { samplers = []; }
  12647. if (defines === void 0) { defines = ""; }
  12648. return this.createEffect({
  12649. vertex: "particles",
  12650. fragmentElement: fragmentName
  12651. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12652. };
  12653. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12654. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12655. context = context || this._gl;
  12656. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12657. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12658. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12659. };
  12660. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12661. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12662. context = context || this._gl;
  12663. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12664. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12665. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12666. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12667. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12668. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12669. return program;
  12670. };
  12671. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12672. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12673. var shaderProgram = context.createProgram();
  12674. if (!shaderProgram) {
  12675. throw new Error("Unable to create program");
  12676. }
  12677. context.attachShader(shaderProgram, vertexShader);
  12678. context.attachShader(shaderProgram, fragmentShader);
  12679. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12680. var transformFeedback = this.createTransformFeedback();
  12681. this.bindTransformFeedback(transformFeedback);
  12682. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12683. shaderProgram.transformFeedback = transformFeedback;
  12684. }
  12685. context.linkProgram(shaderProgram);
  12686. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12687. this.bindTransformFeedback(null);
  12688. }
  12689. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12690. if (!linked) {
  12691. context.validateProgram(shaderProgram);
  12692. var error = context.getProgramInfoLog(shaderProgram);
  12693. if (error) {
  12694. throw new Error(error);
  12695. }
  12696. }
  12697. context.deleteShader(vertexShader);
  12698. context.deleteShader(fragmentShader);
  12699. return shaderProgram;
  12700. };
  12701. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12702. var results = new Array();
  12703. for (var index = 0; index < uniformsNames.length; index++) {
  12704. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12705. }
  12706. return results;
  12707. };
  12708. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12709. var results = [];
  12710. for (var index = 0; index < attributesNames.length; index++) {
  12711. try {
  12712. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12713. }
  12714. catch (e) {
  12715. results.push(-1);
  12716. }
  12717. }
  12718. return results;
  12719. };
  12720. Engine.prototype.enableEffect = function (effect) {
  12721. if (!effect) {
  12722. return;
  12723. }
  12724. // Use program
  12725. this.bindSamplers(effect);
  12726. this._currentEffect = effect;
  12727. if (effect.onBind) {
  12728. effect.onBind(effect);
  12729. }
  12730. effect.onBindObservable.notifyObservers(effect);
  12731. };
  12732. Engine.prototype.setIntArray = function (uniform, array) {
  12733. if (!uniform)
  12734. return;
  12735. this._gl.uniform1iv(uniform, array);
  12736. };
  12737. Engine.prototype.setIntArray2 = function (uniform, array) {
  12738. if (!uniform || array.length % 2 !== 0)
  12739. return;
  12740. this._gl.uniform2iv(uniform, array);
  12741. };
  12742. Engine.prototype.setIntArray3 = function (uniform, array) {
  12743. if (!uniform || array.length % 3 !== 0)
  12744. return;
  12745. this._gl.uniform3iv(uniform, array);
  12746. };
  12747. Engine.prototype.setIntArray4 = function (uniform, array) {
  12748. if (!uniform || array.length % 4 !== 0)
  12749. return;
  12750. this._gl.uniform4iv(uniform, array);
  12751. };
  12752. Engine.prototype.setFloatArray = function (uniform, array) {
  12753. if (!uniform)
  12754. return;
  12755. this._gl.uniform1fv(uniform, array);
  12756. };
  12757. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12758. if (!uniform || array.length % 2 !== 0)
  12759. return;
  12760. this._gl.uniform2fv(uniform, array);
  12761. };
  12762. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12763. if (!uniform || array.length % 3 !== 0)
  12764. return;
  12765. this._gl.uniform3fv(uniform, array);
  12766. };
  12767. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12768. if (!uniform || array.length % 4 !== 0)
  12769. return;
  12770. this._gl.uniform4fv(uniform, array);
  12771. };
  12772. Engine.prototype.setArray = function (uniform, array) {
  12773. if (!uniform)
  12774. return;
  12775. this._gl.uniform1fv(uniform, array);
  12776. };
  12777. Engine.prototype.setArray2 = function (uniform, array) {
  12778. if (!uniform || array.length % 2 !== 0)
  12779. return;
  12780. this._gl.uniform2fv(uniform, array);
  12781. };
  12782. Engine.prototype.setArray3 = function (uniform, array) {
  12783. if (!uniform || array.length % 3 !== 0)
  12784. return;
  12785. this._gl.uniform3fv(uniform, array);
  12786. };
  12787. Engine.prototype.setArray4 = function (uniform, array) {
  12788. if (!uniform || array.length % 4 !== 0)
  12789. return;
  12790. this._gl.uniform4fv(uniform, array);
  12791. };
  12792. Engine.prototype.setMatrices = function (uniform, matrices) {
  12793. if (!uniform)
  12794. return;
  12795. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12796. };
  12797. Engine.prototype.setMatrix = function (uniform, matrix) {
  12798. if (!uniform)
  12799. return;
  12800. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12801. };
  12802. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12803. if (!uniform)
  12804. return;
  12805. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12806. };
  12807. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12808. if (!uniform)
  12809. return;
  12810. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12811. };
  12812. Engine.prototype.setInt = function (uniform, value) {
  12813. if (!uniform)
  12814. return;
  12815. this._gl.uniform1i(uniform, value);
  12816. };
  12817. Engine.prototype.setFloat = function (uniform, value) {
  12818. if (!uniform)
  12819. return;
  12820. this._gl.uniform1f(uniform, value);
  12821. };
  12822. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12823. if (!uniform)
  12824. return;
  12825. this._gl.uniform2f(uniform, x, y);
  12826. };
  12827. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12828. if (!uniform)
  12829. return;
  12830. this._gl.uniform3f(uniform, x, y, z);
  12831. };
  12832. Engine.prototype.setBool = function (uniform, bool) {
  12833. if (!uniform)
  12834. return;
  12835. this._gl.uniform1i(uniform, bool);
  12836. };
  12837. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12838. if (!uniform)
  12839. return;
  12840. this._gl.uniform4f(uniform, x, y, z, w);
  12841. };
  12842. Engine.prototype.setColor3 = function (uniform, color3) {
  12843. if (!uniform)
  12844. return;
  12845. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12846. };
  12847. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12848. if (!uniform)
  12849. return;
  12850. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12851. };
  12852. /**
  12853. * Sets a Color4 on a uniform variable
  12854. * @param uniform defines the uniform location
  12855. * @param color4 defines the value to be set
  12856. */
  12857. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12858. if (!uniform)
  12859. return;
  12860. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12861. };
  12862. // States
  12863. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12864. if (zOffset === void 0) { zOffset = 0; }
  12865. if (reverseSide === void 0) { reverseSide = false; }
  12866. // Culling
  12867. if (this._depthCullingState.cull !== culling || force) {
  12868. this._depthCullingState.cull = culling;
  12869. }
  12870. // Cull face
  12871. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12872. if (this._depthCullingState.cullFace !== cullFace || force) {
  12873. this._depthCullingState.cullFace = cullFace;
  12874. }
  12875. // Z offset
  12876. this.setZOffset(zOffset);
  12877. // Front face
  12878. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12879. if (this._depthCullingState.frontFace !== frontFace || force) {
  12880. this._depthCullingState.frontFace = frontFace;
  12881. }
  12882. };
  12883. Engine.prototype.setZOffset = function (value) {
  12884. this._depthCullingState.zOffset = value;
  12885. };
  12886. Engine.prototype.getZOffset = function () {
  12887. return this._depthCullingState.zOffset;
  12888. };
  12889. Engine.prototype.setDepthBuffer = function (enable) {
  12890. this._depthCullingState.depthTest = enable;
  12891. };
  12892. Engine.prototype.getDepthWrite = function () {
  12893. return this._depthCullingState.depthMask;
  12894. };
  12895. Engine.prototype.setDepthWrite = function (enable) {
  12896. this._depthCullingState.depthMask = enable;
  12897. };
  12898. Engine.prototype.setColorWrite = function (enable) {
  12899. this._gl.colorMask(enable, enable, enable, enable);
  12900. this._colorWrite = enable;
  12901. };
  12902. Engine.prototype.getColorWrite = function () {
  12903. return this._colorWrite;
  12904. };
  12905. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12906. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12907. };
  12908. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12909. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12910. if (this._alphaMode === mode) {
  12911. return;
  12912. }
  12913. switch (mode) {
  12914. case Engine.ALPHA_DISABLE:
  12915. this._alphaState.alphaBlend = false;
  12916. break;
  12917. case Engine.ALPHA_PREMULTIPLIED:
  12918. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12919. this._alphaState.alphaBlend = true;
  12920. break;
  12921. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12922. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12923. this._alphaState.alphaBlend = true;
  12924. break;
  12925. case Engine.ALPHA_COMBINE:
  12926. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12927. this._alphaState.alphaBlend = true;
  12928. break;
  12929. case Engine.ALPHA_ONEONE:
  12930. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12931. this._alphaState.alphaBlend = true;
  12932. break;
  12933. case Engine.ALPHA_ADD:
  12934. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12935. this._alphaState.alphaBlend = true;
  12936. break;
  12937. case Engine.ALPHA_SUBTRACT:
  12938. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12939. this._alphaState.alphaBlend = true;
  12940. break;
  12941. case Engine.ALPHA_MULTIPLY:
  12942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12943. this._alphaState.alphaBlend = true;
  12944. break;
  12945. case Engine.ALPHA_MAXIMIZED:
  12946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12947. this._alphaState.alphaBlend = true;
  12948. break;
  12949. case Engine.ALPHA_INTERPOLATE:
  12950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12951. this._alphaState.alphaBlend = true;
  12952. break;
  12953. case Engine.ALPHA_SCREENMODE:
  12954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12955. this._alphaState.alphaBlend = true;
  12956. break;
  12957. }
  12958. if (!noDepthWriteChange) {
  12959. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12960. }
  12961. this._alphaMode = mode;
  12962. };
  12963. Engine.prototype.getAlphaMode = function () {
  12964. return this._alphaMode;
  12965. };
  12966. // Textures
  12967. Engine.prototype.wipeCaches = function (bruteForce) {
  12968. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12969. return;
  12970. }
  12971. this._currentEffect = null;
  12972. // 6/8/2017: deltakosh: Should not be required anymore.
  12973. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12974. if (bruteForce) {
  12975. this.resetTextureCache();
  12976. this._currentProgram = null;
  12977. this._stencilState.reset();
  12978. this._depthCullingState.reset();
  12979. this.setDepthFunctionToLessOrEqual();
  12980. this._alphaState.reset();
  12981. }
  12982. this._resetVertexBufferBinding();
  12983. this._cachedIndexBuffer = null;
  12984. this._cachedEffectForVertexBuffers = null;
  12985. this._unbindVertexArrayObject();
  12986. this.bindIndexBuffer(null);
  12987. };
  12988. /**
  12989. * Set the compressed texture format to use, based on the formats you have, and the formats
  12990. * supported by the hardware / browser.
  12991. *
  12992. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12993. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12994. * to API arguments needed to compressed textures. This puts the burden on the container
  12995. * generator to house the arcane code for determining these for current & future formats.
  12996. *
  12997. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12998. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12999. *
  13000. * Note: The result of this call is not taken into account when a texture is base64.
  13001. *
  13002. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13003. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13004. *
  13005. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13006. * @returns The extension selected.
  13007. */
  13008. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13009. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13010. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13011. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13012. return this._textureFormatInUse = this._texturesSupported[i];
  13013. }
  13014. }
  13015. }
  13016. // actively set format to nothing, to allow this to be called more than once
  13017. // and possibly fail the 2nd time
  13018. this._textureFormatInUse = null;
  13019. return null;
  13020. };
  13021. Engine.prototype._createTexture = function () {
  13022. var texture = this._gl.createTexture();
  13023. if (!texture) {
  13024. throw new Error("Unable to create texture");
  13025. }
  13026. return texture;
  13027. };
  13028. /**
  13029. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13030. * @param {string} urlArg- This contains one of the following:
  13031. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13032. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13033. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13034. *
  13035. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13036. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13037. * @param {Scene} scene- Needed for loading to the correct scene.
  13038. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13039. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13040. * @param {callback} onError- Optional callback to be called upon failure.
  13041. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13042. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13043. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13044. *
  13045. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13046. */
  13047. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13048. var _this = this;
  13049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13050. if (onLoad === void 0) { onLoad = null; }
  13051. if (onError === void 0) { onError = null; }
  13052. if (buffer === void 0) { buffer = null; }
  13053. if (fallBack === void 0) { fallBack = null; }
  13054. if (format === void 0) { format = null; }
  13055. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13056. var fromData = url.substr(0, 5) === "data:";
  13057. var fromBlob = url.substr(0, 5) === "blob:";
  13058. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13059. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13060. // establish the file extension, if possible
  13061. var lastDot = url.lastIndexOf('.');
  13062. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13063. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13064. var isTGA = (extension.indexOf(".tga") === 0);
  13065. // determine if a ktx file should be substituted
  13066. var isKTX = false;
  13067. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13068. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13069. isKTX = true;
  13070. }
  13071. if (scene) {
  13072. scene._addPendingData(texture);
  13073. }
  13074. texture.url = url;
  13075. texture.generateMipMaps = !noMipmap;
  13076. texture.samplingMode = samplingMode;
  13077. texture.invertY = invertY;
  13078. if (!this._doNotHandleContextLost) {
  13079. // Keep a link to the buffer only if we plan to handle context lost
  13080. texture._buffer = buffer;
  13081. }
  13082. var onLoadObserver = null;
  13083. if (onLoad && !fallBack) {
  13084. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13085. }
  13086. if (!fallBack)
  13087. this._internalTexturesCache.push(texture);
  13088. var onerror = function (message, exception) {
  13089. if (scene) {
  13090. scene._removePendingData(texture);
  13091. }
  13092. if (onLoadObserver) {
  13093. texture.onLoadedObservable.remove(onLoadObserver);
  13094. }
  13095. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13096. if (isKTX) {
  13097. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13098. }
  13099. else if (BABYLON.Tools.UseFallbackTexture) {
  13100. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13101. }
  13102. if (onError) {
  13103. onError(message || "Unknown error", exception);
  13104. }
  13105. };
  13106. var callback = null;
  13107. // processing for non-image formats
  13108. if (isKTX || isTGA || isDDS) {
  13109. if (isKTX) {
  13110. callback = function (data) {
  13111. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13112. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13113. ktx.uploadLevels(_this._gl, !noMipmap);
  13114. return false;
  13115. }, samplingMode);
  13116. };
  13117. }
  13118. else if (isTGA) {
  13119. callback = function (arrayBuffer) {
  13120. var data = new Uint8Array(arrayBuffer);
  13121. var header = BABYLON.TGATools.GetTGAHeader(data);
  13122. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13123. BABYLON.TGATools.UploadContent(_this._gl, data);
  13124. return false;
  13125. }, samplingMode);
  13126. };
  13127. }
  13128. else if (isDDS) {
  13129. callback = function (data) {
  13130. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13131. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13132. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13133. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13134. return false;
  13135. }, samplingMode);
  13136. };
  13137. }
  13138. if (!buffer) {
  13139. this._loadFile(url, function (data) {
  13140. if (callback) {
  13141. callback(data);
  13142. }
  13143. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13144. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13145. });
  13146. }
  13147. else {
  13148. if (callback) {
  13149. callback(buffer);
  13150. }
  13151. }
  13152. // image format processing
  13153. }
  13154. else {
  13155. var onload = function (img) {
  13156. if (fromBlob && !_this._doNotHandleContextLost) {
  13157. // We need to store the image if we need to rebuild the texture
  13158. // in case of a webgl context lost
  13159. texture._buffer = img;
  13160. }
  13161. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13162. var gl = _this._gl;
  13163. var isPot = (img.width === potWidth && img.height === potHeight);
  13164. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13165. if (isPot) {
  13166. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13167. return false;
  13168. }
  13169. // Using shaders to rescale because canvas.drawImage is lossy
  13170. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13171. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13172. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13173. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13174. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13177. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13178. _this._releaseTexture(source);
  13179. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13180. continuationCallback();
  13181. });
  13182. return true;
  13183. }, samplingMode);
  13184. };
  13185. if (!fromData || isBase64)
  13186. if (buffer instanceof HTMLImageElement) {
  13187. onload(buffer);
  13188. }
  13189. else {
  13190. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13191. }
  13192. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13193. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13194. else
  13195. onload(buffer);
  13196. }
  13197. return texture;
  13198. };
  13199. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13200. var _this = this;
  13201. var rtt = this.createRenderTargetTexture({
  13202. width: destination.width,
  13203. height: destination.height,
  13204. }, {
  13205. generateMipMaps: false,
  13206. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13207. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13208. generateDepthBuffer: false,
  13209. generateStencilBuffer: false
  13210. });
  13211. if (!this._rescalePostProcess) {
  13212. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13213. }
  13214. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13215. _this._rescalePostProcess.onApply = function (effect) {
  13216. effect._bindTexture("textureSampler", source);
  13217. };
  13218. var hostingScene = scene;
  13219. if (!hostingScene) {
  13220. hostingScene = _this.scenes[_this.scenes.length - 1];
  13221. }
  13222. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13223. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13224. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13225. _this.unBindFramebuffer(rtt);
  13226. _this._releaseTexture(rtt);
  13227. if (onComplete) {
  13228. onComplete();
  13229. }
  13230. });
  13231. };
  13232. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13233. if (compression === void 0) { compression = null; }
  13234. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13235. if (!texture) {
  13236. return;
  13237. }
  13238. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13239. var internalFormat = this._getInternalFormat(format);
  13240. var textureType = this._getWebGLTextureType(type);
  13241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13242. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13243. if (!this._doNotHandleContextLost) {
  13244. texture._bufferView = data;
  13245. texture.format = format;
  13246. texture.type = type;
  13247. texture.invertY = invertY;
  13248. texture._compression = compression;
  13249. }
  13250. if (texture.width % 4 !== 0) {
  13251. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13252. }
  13253. if (compression && data) {
  13254. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13255. }
  13256. else {
  13257. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13258. }
  13259. if (texture.generateMipMaps) {
  13260. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13261. }
  13262. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13263. // this.resetTextureCache();
  13264. texture.isReady = true;
  13265. };
  13266. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13267. if (compression === void 0) { compression = null; }
  13268. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13269. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13270. texture.baseWidth = width;
  13271. texture.baseHeight = height;
  13272. texture.width = width;
  13273. texture.height = height;
  13274. texture.format = format;
  13275. texture.generateMipMaps = generateMipMaps;
  13276. texture.samplingMode = samplingMode;
  13277. texture.invertY = invertY;
  13278. texture._compression = compression;
  13279. texture.type = type;
  13280. if (!this._doNotHandleContextLost) {
  13281. texture._bufferView = data;
  13282. }
  13283. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13284. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13285. // Filters
  13286. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13287. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13288. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13289. if (generateMipMaps) {
  13290. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13291. }
  13292. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13293. this._internalTexturesCache.push(texture);
  13294. return texture;
  13295. };
  13296. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13297. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13298. texture.baseWidth = width;
  13299. texture.baseHeight = height;
  13300. if (generateMipMaps) {
  13301. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13302. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13303. }
  13304. // this.resetTextureCache();
  13305. texture.width = width;
  13306. texture.height = height;
  13307. texture.isReady = false;
  13308. texture.generateMipMaps = generateMipMaps;
  13309. texture.samplingMode = samplingMode;
  13310. this.updateTextureSamplingMode(samplingMode, texture);
  13311. this._internalTexturesCache.push(texture);
  13312. return texture;
  13313. };
  13314. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13315. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13316. if (texture.isCube) {
  13317. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13318. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13319. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13320. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13321. }
  13322. else if (texture.is3D) {
  13323. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13324. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13325. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13326. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13327. }
  13328. else {
  13329. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13330. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13332. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13333. }
  13334. texture.samplingMode = samplingMode;
  13335. };
  13336. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13337. if (premulAlpha === void 0) { premulAlpha = false; }
  13338. if (!texture) {
  13339. return;
  13340. }
  13341. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13342. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13343. if (premulAlpha) {
  13344. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13345. }
  13346. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13347. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13348. if (texture.generateMipMaps) {
  13349. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13350. }
  13351. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13352. if (premulAlpha) {
  13353. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13354. }
  13355. texture.isReady = true;
  13356. };
  13357. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13358. if (!texture || texture._isDisabled) {
  13359. return;
  13360. }
  13361. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13362. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13363. try {
  13364. // Testing video texture support
  13365. if (this._videoTextureSupported === undefined) {
  13366. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13367. if (this._gl.getError() !== 0) {
  13368. this._videoTextureSupported = false;
  13369. }
  13370. else {
  13371. this._videoTextureSupported = true;
  13372. }
  13373. }
  13374. // Copy video through the current working canvas if video texture is not supported
  13375. if (!this._videoTextureSupported) {
  13376. if (!texture._workingCanvas) {
  13377. texture._workingCanvas = document.createElement("canvas");
  13378. var context = texture._workingCanvas.getContext("2d");
  13379. if (!context) {
  13380. throw new Error("Unable to get 2d context");
  13381. }
  13382. texture._workingContext = context;
  13383. texture._workingCanvas.width = texture.width;
  13384. texture._workingCanvas.height = texture.height;
  13385. }
  13386. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13387. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13388. }
  13389. else {
  13390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13391. }
  13392. if (texture.generateMipMaps) {
  13393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13394. }
  13395. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13396. // this.resetTextureCache();
  13397. texture.isReady = true;
  13398. }
  13399. catch (ex) {
  13400. // Something unexpected
  13401. // Let's disable the texture
  13402. texture._isDisabled = true;
  13403. }
  13404. };
  13405. /**
  13406. * Updates a depth texture Comparison Mode and Function.
  13407. * If the comparison Function is equal to 0, the mode will be set to none.
  13408. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13409. * @param texture The texture to set the comparison function for
  13410. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13411. */
  13412. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13413. if (this.webGLVersion === 1) {
  13414. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13415. return;
  13416. }
  13417. var gl = this._gl;
  13418. if (texture.isCube) {
  13419. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13420. if (comparisonFunction === 0) {
  13421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13423. }
  13424. else {
  13425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13426. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13427. }
  13428. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13429. }
  13430. else {
  13431. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13432. if (comparisonFunction === 0) {
  13433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13435. }
  13436. else {
  13437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13439. }
  13440. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13441. }
  13442. texture._comparisonFunction = comparisonFunction;
  13443. };
  13444. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13445. var width = size.width || size;
  13446. var height = size.height || size;
  13447. internalTexture.baseWidth = width;
  13448. internalTexture.baseHeight = height;
  13449. internalTexture.width = width;
  13450. internalTexture.height = height;
  13451. internalTexture.isReady = true;
  13452. internalTexture.samples = 1;
  13453. internalTexture.generateMipMaps = false;
  13454. internalTexture._generateDepthBuffer = true;
  13455. internalTexture._generateStencilBuffer = generateStencil;
  13456. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13457. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13458. internalTexture._comparisonFunction = comparisonFunction;
  13459. var gl = this._gl;
  13460. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13461. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13462. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13463. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13464. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13465. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13466. if (comparisonFunction === 0) {
  13467. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13468. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13469. }
  13470. else {
  13471. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13472. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13473. }
  13474. };
  13475. /**
  13476. * Creates a depth stencil texture.
  13477. * This is only available in WebGL 2 or with the depth texture extension available.
  13478. * @param size The size of face edge in the texture.
  13479. * @param options The options defining the texture.
  13480. * @returns The texture
  13481. */
  13482. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13483. if (options.isCube) {
  13484. var width = size.width || size;
  13485. return this._createDepthStencilCubeTexture(width, options);
  13486. }
  13487. else {
  13488. return this._createDepthStencilTexture(size, options);
  13489. }
  13490. };
  13491. /**
  13492. * Creates a depth stencil texture.
  13493. * This is only available in WebGL 2 or with the depth texture extension available.
  13494. * @param size The size of face edge in the texture.
  13495. * @param options The options defining the texture.
  13496. * @returns The texture
  13497. */
  13498. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13499. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13500. if (!this._caps.depthTextureExtension) {
  13501. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13502. return internalTexture;
  13503. }
  13504. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13505. var gl = this._gl;
  13506. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13507. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13508. if (this.webGLVersion > 1) {
  13509. if (internalOptions.generateStencil) {
  13510. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13511. }
  13512. else {
  13513. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13514. }
  13515. }
  13516. else {
  13517. if (internalOptions.generateStencil) {
  13518. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13519. }
  13520. else {
  13521. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13522. }
  13523. }
  13524. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13525. return internalTexture;
  13526. };
  13527. /**
  13528. * Creates a depth stencil cube texture.
  13529. * This is only available in WebGL 2.
  13530. * @param size The size of face edge in the cube texture.
  13531. * @param options The options defining the cube texture.
  13532. * @returns The cube texture
  13533. */
  13534. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13535. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13536. internalTexture.isCube = true;
  13537. if (this.webGLVersion === 1) {
  13538. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13539. return internalTexture;
  13540. }
  13541. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13542. var gl = this._gl;
  13543. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13544. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13545. // Create the depth/stencil buffer
  13546. for (var face = 0; face < 6; face++) {
  13547. if (internalOptions.generateStencil) {
  13548. 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);
  13549. }
  13550. else {
  13551. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13552. }
  13553. }
  13554. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13555. return internalTexture;
  13556. };
  13557. /**
  13558. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13559. * @param renderTarget The render target to set the frame buffer for
  13560. */
  13561. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13562. // Create the framebuffer
  13563. var internalTexture = renderTarget.getInternalTexture();
  13564. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13565. return;
  13566. }
  13567. var gl = this._gl;
  13568. var depthStencilTexture = renderTarget.depthStencilTexture;
  13569. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13570. if (depthStencilTexture.isCube) {
  13571. if (depthStencilTexture._generateStencilBuffer) {
  13572. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13573. }
  13574. else {
  13575. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13576. }
  13577. }
  13578. else {
  13579. if (depthStencilTexture._generateStencilBuffer) {
  13580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13581. }
  13582. else {
  13583. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13584. }
  13585. }
  13586. this.bindUnboundFramebuffer(null);
  13587. };
  13588. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13589. var fullOptions = new RenderTargetCreationOptions();
  13590. if (options !== undefined && typeof options === "object") {
  13591. fullOptions.generateMipMaps = options.generateMipMaps;
  13592. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13593. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13594. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13595. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13596. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13597. }
  13598. else {
  13599. fullOptions.generateMipMaps = options;
  13600. fullOptions.generateDepthBuffer = true;
  13601. fullOptions.generateStencilBuffer = false;
  13602. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13603. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13604. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13605. }
  13606. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13607. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13608. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13609. }
  13610. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13611. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13612. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13613. }
  13614. var gl = this._gl;
  13615. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13616. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13617. var width = size.width || size;
  13618. var height = size.height || size;
  13619. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13620. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13621. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13622. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13623. }
  13624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13628. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13629. // Create the framebuffer
  13630. var framebuffer = gl.createFramebuffer();
  13631. this.bindUnboundFramebuffer(framebuffer);
  13632. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13633. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13634. if (fullOptions.generateMipMaps) {
  13635. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13636. }
  13637. // Unbind
  13638. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13639. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13640. this.bindUnboundFramebuffer(null);
  13641. texture._framebuffer = framebuffer;
  13642. texture.baseWidth = width;
  13643. texture.baseHeight = height;
  13644. texture.width = width;
  13645. texture.height = height;
  13646. texture.isReady = true;
  13647. texture.samples = 1;
  13648. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13649. texture.samplingMode = fullOptions.samplingMode;
  13650. texture.type = fullOptions.type;
  13651. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13652. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13653. // this.resetTextureCache();
  13654. this._internalTexturesCache.push(texture);
  13655. return texture;
  13656. };
  13657. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13658. var generateMipMaps = false;
  13659. var generateDepthBuffer = true;
  13660. var generateStencilBuffer = false;
  13661. var generateDepthTexture = false;
  13662. var textureCount = 1;
  13663. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13664. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13665. var types = [], samplingModes = [];
  13666. if (options !== undefined) {
  13667. generateMipMaps = options.generateMipMaps;
  13668. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13669. generateStencilBuffer = options.generateStencilBuffer;
  13670. generateDepthTexture = options.generateDepthTexture;
  13671. textureCount = options.textureCount || 1;
  13672. if (options.types) {
  13673. types = options.types;
  13674. }
  13675. if (options.samplingModes) {
  13676. samplingModes = options.samplingModes;
  13677. }
  13678. }
  13679. var gl = this._gl;
  13680. // Create the framebuffer
  13681. var framebuffer = gl.createFramebuffer();
  13682. this.bindUnboundFramebuffer(framebuffer);
  13683. var width = size.width || size;
  13684. var height = size.height || size;
  13685. var textures = [];
  13686. var attachments = [];
  13687. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13688. for (var i = 0; i < textureCount; i++) {
  13689. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13690. var type = types[i] || defaultType;
  13691. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13692. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13693. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13694. }
  13695. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13696. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13697. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13698. }
  13699. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13700. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13701. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13702. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13703. }
  13704. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13705. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13706. textures.push(texture);
  13707. attachments.push(attachment);
  13708. gl.activeTexture(gl["TEXTURE" + i]);
  13709. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13714. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13715. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13716. if (generateMipMaps) {
  13717. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13718. }
  13719. // Unbind
  13720. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13721. texture._framebuffer = framebuffer;
  13722. texture._depthStencilBuffer = depthStencilBuffer;
  13723. texture.baseWidth = width;
  13724. texture.baseHeight = height;
  13725. texture.width = width;
  13726. texture.height = height;
  13727. texture.isReady = true;
  13728. texture.samples = 1;
  13729. texture.generateMipMaps = generateMipMaps;
  13730. texture.samplingMode = samplingMode;
  13731. texture.type = type;
  13732. texture._generateDepthBuffer = generateDepthBuffer;
  13733. texture._generateStencilBuffer = generateStencilBuffer;
  13734. texture._attachments = attachments;
  13735. this._internalTexturesCache.push(texture);
  13736. }
  13737. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13738. // Depth texture
  13739. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13740. gl.activeTexture(gl.TEXTURE0);
  13741. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13744. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13745. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13746. 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);
  13747. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13748. depthTexture._framebuffer = framebuffer;
  13749. depthTexture.baseWidth = width;
  13750. depthTexture.baseHeight = height;
  13751. depthTexture.width = width;
  13752. depthTexture.height = height;
  13753. depthTexture.isReady = true;
  13754. depthTexture.samples = 1;
  13755. depthTexture.generateMipMaps = generateMipMaps;
  13756. depthTexture.samplingMode = gl.NEAREST;
  13757. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13758. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13759. textures.push(depthTexture);
  13760. this._internalTexturesCache.push(depthTexture);
  13761. }
  13762. gl.drawBuffers(attachments);
  13763. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13764. this.bindUnboundFramebuffer(null);
  13765. this.resetTextureCache();
  13766. return textures;
  13767. };
  13768. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13769. if (samples === void 0) { samples = 1; }
  13770. var depthStencilBuffer = null;
  13771. var gl = this._gl;
  13772. // Create the depth/stencil buffer
  13773. if (generateStencilBuffer) {
  13774. depthStencilBuffer = gl.createRenderbuffer();
  13775. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13776. if (samples > 1) {
  13777. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13778. }
  13779. else {
  13780. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13781. }
  13782. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13783. }
  13784. else if (generateDepthBuffer) {
  13785. depthStencilBuffer = gl.createRenderbuffer();
  13786. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13787. if (samples > 1) {
  13788. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13789. }
  13790. else {
  13791. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13792. }
  13793. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13794. }
  13795. return depthStencilBuffer;
  13796. };
  13797. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13798. if (this.webGLVersion < 2 || !texture) {
  13799. return 1;
  13800. }
  13801. if (texture.samples === samples) {
  13802. return samples;
  13803. }
  13804. var gl = this._gl;
  13805. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13806. // Dispose previous render buffers
  13807. if (texture._depthStencilBuffer) {
  13808. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13809. texture._depthStencilBuffer = null;
  13810. }
  13811. if (texture._MSAAFramebuffer) {
  13812. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13813. texture._MSAAFramebuffer = null;
  13814. }
  13815. if (texture._MSAARenderBuffer) {
  13816. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13817. texture._MSAARenderBuffer = null;
  13818. }
  13819. if (samples > 1) {
  13820. var framebuffer = gl.createFramebuffer();
  13821. if (!framebuffer) {
  13822. throw new Error("Unable to create multi sampled framebuffer");
  13823. }
  13824. texture._MSAAFramebuffer = framebuffer;
  13825. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13826. var colorRenderbuffer = gl.createRenderbuffer();
  13827. if (!colorRenderbuffer) {
  13828. throw new Error("Unable to create multi sampled framebuffer");
  13829. }
  13830. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13831. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13832. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13833. texture._MSAARenderBuffer = colorRenderbuffer;
  13834. }
  13835. else {
  13836. this.bindUnboundFramebuffer(texture._framebuffer);
  13837. }
  13838. texture.samples = samples;
  13839. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13840. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13841. this.bindUnboundFramebuffer(null);
  13842. return samples;
  13843. };
  13844. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13845. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13846. return 1;
  13847. }
  13848. if (textures[0].samples === samples) {
  13849. return samples;
  13850. }
  13851. var gl = this._gl;
  13852. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13853. // Dispose previous render buffers
  13854. if (textures[0]._depthStencilBuffer) {
  13855. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13856. textures[0]._depthStencilBuffer = null;
  13857. }
  13858. if (textures[0]._MSAAFramebuffer) {
  13859. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13860. textures[0]._MSAAFramebuffer = null;
  13861. }
  13862. for (var i = 0; i < textures.length; i++) {
  13863. if (textures[i]._MSAARenderBuffer) {
  13864. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13865. textures[i]._MSAARenderBuffer = null;
  13866. }
  13867. }
  13868. if (samples > 1) {
  13869. var framebuffer = gl.createFramebuffer();
  13870. if (!framebuffer) {
  13871. throw new Error("Unable to create multi sampled framebuffer");
  13872. }
  13873. this.bindUnboundFramebuffer(framebuffer);
  13874. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13875. var attachments = [];
  13876. for (var i = 0; i < textures.length; i++) {
  13877. var texture = textures[i];
  13878. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13879. var colorRenderbuffer = gl.createRenderbuffer();
  13880. if (!colorRenderbuffer) {
  13881. throw new Error("Unable to create multi sampled framebuffer");
  13882. }
  13883. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13884. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13885. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13886. texture._MSAAFramebuffer = framebuffer;
  13887. texture._MSAARenderBuffer = colorRenderbuffer;
  13888. texture.samples = samples;
  13889. texture._depthStencilBuffer = depthStencilBuffer;
  13890. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13891. attachments.push(attachment);
  13892. }
  13893. gl.drawBuffers(attachments);
  13894. }
  13895. else {
  13896. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13897. }
  13898. this.bindUnboundFramebuffer(null);
  13899. return samples;
  13900. };
  13901. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13902. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13903. };
  13904. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13905. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13906. };
  13907. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13908. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13909. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13910. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13911. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13912. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13913. }
  13914. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13915. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13916. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13917. }
  13918. var gl = this._gl;
  13919. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13920. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13921. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13922. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13923. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13924. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13925. }
  13926. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13929. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13930. for (var face = 0; face < 6; face++) {
  13931. 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);
  13932. }
  13933. // Create the framebuffer
  13934. var framebuffer = gl.createFramebuffer();
  13935. this.bindUnboundFramebuffer(framebuffer);
  13936. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13937. // MipMaps
  13938. if (fullOptions.generateMipMaps) {
  13939. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13940. }
  13941. // Unbind
  13942. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13943. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13944. this.bindUnboundFramebuffer(null);
  13945. texture._framebuffer = framebuffer;
  13946. texture.width = size;
  13947. texture.height = size;
  13948. texture.isReady = true;
  13949. texture.isCube = true;
  13950. texture.samples = 1;
  13951. texture.generateMipMaps = fullOptions.generateMipMaps;
  13952. texture.samplingMode = fullOptions.samplingMode;
  13953. texture.type = fullOptions.type;
  13954. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13955. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13956. this._internalTexturesCache.push(texture);
  13957. return texture;
  13958. };
  13959. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13960. var _this = this;
  13961. if (onLoad === void 0) { onLoad = null; }
  13962. if (onError === void 0) { onError = null; }
  13963. if (forcedExtension === void 0) { forcedExtension = null; }
  13964. var callback = function (loadData) {
  13965. if (!loadData) {
  13966. if (onLoad) {
  13967. onLoad(null);
  13968. }
  13969. return;
  13970. }
  13971. var texture = loadData.texture;
  13972. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13973. texture._lodGenerationScale = scale;
  13974. texture._lodGenerationOffset = offset;
  13975. if (_this._caps.textureLOD) {
  13976. // Do not add extra process if texture lod is supported.
  13977. if (onLoad) {
  13978. onLoad(texture);
  13979. }
  13980. return;
  13981. }
  13982. var mipSlices = 3;
  13983. var gl = _this._gl;
  13984. var width = loadData.width;
  13985. if (!width) {
  13986. return;
  13987. }
  13988. var textures = [];
  13989. for (var i = 0; i < mipSlices; i++) {
  13990. //compute LOD from even spacing in smoothness (matching shader calculation)
  13991. var smoothness = i / (mipSlices - 1);
  13992. var roughness = 1 - smoothness;
  13993. var minLODIndex = offset; // roughness = 0
  13994. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13995. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13996. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13997. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13998. glTextureFromLod.isCube = true;
  13999. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14004. if (loadData.isDDS) {
  14005. var info = loadData.info;
  14006. var data = loadData.data;
  14007. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14008. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14009. }
  14010. else {
  14011. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14012. }
  14013. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14014. // Wrap in a base texture for easy binding.
  14015. var lodTexture = new BABYLON.BaseTexture(scene);
  14016. lodTexture.isCube = true;
  14017. lodTexture._texture = glTextureFromLod;
  14018. glTextureFromLod.isReady = true;
  14019. textures.push(lodTexture);
  14020. }
  14021. texture._lodTextureHigh = textures[2];
  14022. texture._lodTextureMid = textures[1];
  14023. texture._lodTextureLow = textures[0];
  14024. if (onLoad) {
  14025. onLoad(texture);
  14026. }
  14027. };
  14028. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14029. };
  14030. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14031. var _this = this;
  14032. if (onLoad === void 0) { onLoad = null; }
  14033. if (onError === void 0) { onError = null; }
  14034. if (forcedExtension === void 0) { forcedExtension = null; }
  14035. var gl = this._gl;
  14036. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14037. texture.isCube = true;
  14038. texture.url = rootUrl;
  14039. texture.generateMipMaps = !noMipmap;
  14040. if (!this._doNotHandleContextLost) {
  14041. texture._extension = forcedExtension;
  14042. texture._files = files;
  14043. }
  14044. var isKTX = false;
  14045. var isDDS = false;
  14046. var lastDot = rootUrl.lastIndexOf('.');
  14047. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14048. if (this._textureFormatInUse) {
  14049. extension = this._textureFormatInUse;
  14050. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14051. isKTX = true;
  14052. }
  14053. else {
  14054. isDDS = (extension === ".dds");
  14055. }
  14056. var onerror = function (request, exception) {
  14057. if (onError && request) {
  14058. onError(request.status + " " + request.statusText, exception);
  14059. }
  14060. };
  14061. if (isKTX) {
  14062. this._loadFile(rootUrl, function (data) {
  14063. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14064. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14065. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14066. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14067. ktx.uploadLevels(_this._gl, !noMipmap);
  14068. _this.setCubeMapTextureParams(gl, loadMipmap);
  14069. texture.width = ktx.pixelWidth;
  14070. texture.height = ktx.pixelHeight;
  14071. texture.isReady = true;
  14072. }, undefined, undefined, true, onerror);
  14073. }
  14074. else if (isDDS) {
  14075. if (files && files.length === 6) {
  14076. this._cascadeLoadFiles(scene, function (imgs) {
  14077. var info;
  14078. var loadMipmap = false;
  14079. var width = 0;
  14080. for (var index = 0; index < imgs.length; index++) {
  14081. var data = imgs[index];
  14082. info = BABYLON.DDSTools.GetDDSInfo(data);
  14083. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14084. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14086. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14087. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14088. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14089. }
  14090. texture.width = info.width;
  14091. texture.height = info.height;
  14092. texture.type = info.textureType;
  14093. width = info.width;
  14094. }
  14095. _this.setCubeMapTextureParams(gl, loadMipmap);
  14096. texture.isReady = true;
  14097. if (onLoad) {
  14098. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14099. }
  14100. }, files, onError);
  14101. }
  14102. else {
  14103. this._loadFile(rootUrl, function (data) {
  14104. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14105. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14106. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14107. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14108. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14109. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14110. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14111. }
  14112. _this.setCubeMapTextureParams(gl, loadMipmap);
  14113. texture.width = info.width;
  14114. texture.height = info.height;
  14115. texture.isReady = true;
  14116. texture.type = info.textureType;
  14117. if (onLoad) {
  14118. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14119. }
  14120. }, undefined, undefined, true, onerror);
  14121. }
  14122. }
  14123. else {
  14124. if (!files) {
  14125. throw new Error("Cannot load cubemap because files were not defined");
  14126. }
  14127. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14128. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14129. var height = width;
  14130. _this._prepareWorkingCanvas();
  14131. if (!_this._workingCanvas || !_this._workingContext) {
  14132. return;
  14133. }
  14134. _this._workingCanvas.width = width;
  14135. _this._workingCanvas.height = height;
  14136. var faces = [
  14137. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14138. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14139. ];
  14140. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14141. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14142. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14143. for (var index = 0; index < faces.length; index++) {
  14144. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14145. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14146. }
  14147. if (!noMipmap) {
  14148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14149. }
  14150. _this.setCubeMapTextureParams(gl, !noMipmap);
  14151. texture.width = width;
  14152. texture.height = height;
  14153. texture.isReady = true;
  14154. if (format) {
  14155. texture.format = format;
  14156. }
  14157. texture.onLoadedObservable.notifyObservers(texture);
  14158. texture.onLoadedObservable.clear();
  14159. if (onLoad) {
  14160. onLoad();
  14161. }
  14162. }, files, onError);
  14163. }
  14164. this._internalTexturesCache.push(texture);
  14165. return texture;
  14166. };
  14167. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14171. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14172. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14173. // this.resetTextureCache();
  14174. };
  14175. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14176. if (compression === void 0) { compression = null; }
  14177. if (level === void 0) { level = 0; }
  14178. texture._bufferViewArray = data;
  14179. texture.format = format;
  14180. texture.type = type;
  14181. texture.invertY = invertY;
  14182. texture._compression = compression;
  14183. var gl = this._gl;
  14184. var textureType = this._getWebGLTextureType(type);
  14185. var internalFormat = this._getInternalFormat(format);
  14186. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14187. var needConversion = false;
  14188. if (internalFormat === gl.RGB) {
  14189. internalFormat = gl.RGBA;
  14190. needConversion = true;
  14191. }
  14192. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14193. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14194. if (texture.width % 4 !== 0) {
  14195. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14196. }
  14197. // Data are known to be in +X +Y +Z -X -Y -Z
  14198. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14199. var faceData = data[faceIndex];
  14200. if (compression) {
  14201. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14202. }
  14203. else {
  14204. if (needConversion) {
  14205. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14206. }
  14207. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14208. }
  14209. }
  14210. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14211. if (isPot && texture.generateMipMaps && level === 0) {
  14212. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14213. }
  14214. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14215. // this.resetTextureCache();
  14216. texture.isReady = true;
  14217. };
  14218. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14219. if (compression === void 0) { compression = null; }
  14220. var gl = this._gl;
  14221. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14222. texture.isCube = true;
  14223. texture.generateMipMaps = generateMipMaps;
  14224. texture.format = format;
  14225. texture.type = type;
  14226. if (!this._doNotHandleContextLost) {
  14227. texture._bufferViewArray = data;
  14228. }
  14229. var textureType = this._getWebGLTextureType(type);
  14230. var internalFormat = this._getInternalFormat(format);
  14231. if (internalFormat === gl.RGB) {
  14232. internalFormat = gl.RGBA;
  14233. }
  14234. var width = size;
  14235. var height = width;
  14236. texture.width = width;
  14237. texture.height = height;
  14238. // Double check on POT to generate Mips.
  14239. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14240. if (!isPot) {
  14241. generateMipMaps = false;
  14242. }
  14243. // Upload data if needed. The texture won't be ready until then.
  14244. if (data) {
  14245. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14246. }
  14247. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14248. // Filters
  14249. if (data && generateMipMaps) {
  14250. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14251. }
  14252. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14253. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14254. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14255. }
  14256. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14257. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14258. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14259. }
  14260. else {
  14261. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14262. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14263. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14264. }
  14265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14267. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14268. return texture;
  14269. };
  14270. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14271. var _this = this;
  14272. if (onLoad === void 0) { onLoad = null; }
  14273. if (onError === void 0) { onError = null; }
  14274. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14275. if (invertY === void 0) { invertY = false; }
  14276. var gl = this._gl;
  14277. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14278. scene._addPendingData(texture);
  14279. texture.url = url;
  14280. this._internalTexturesCache.push(texture);
  14281. var onerror = function (request, exception) {
  14282. scene._removePendingData(texture);
  14283. if (onError && request) {
  14284. onError(request.status + " " + request.statusText, exception);
  14285. }
  14286. };
  14287. var internalCallback = function (data) {
  14288. var width = texture.width;
  14289. var faceDataArrays = callback(data);
  14290. if (!faceDataArrays) {
  14291. return;
  14292. }
  14293. if (mipmmapGenerator) {
  14294. var textureType = _this._getWebGLTextureType(type);
  14295. var internalFormat = _this._getInternalFormat(format);
  14296. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14297. var needConversion = false;
  14298. if (internalFormat === gl.RGB) {
  14299. internalFormat = gl.RGBA;
  14300. needConversion = true;
  14301. }
  14302. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14303. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14304. var mipData = mipmmapGenerator(faceDataArrays);
  14305. for (var level = 0; level < mipData.length; level++) {
  14306. var mipSize = width >> level;
  14307. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14308. var mipFaceData = mipData[level][faceIndex];
  14309. if (needConversion) {
  14310. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14311. }
  14312. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14313. }
  14314. }
  14315. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14316. }
  14317. else {
  14318. texture.generateMipMaps = !noMipmap;
  14319. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14320. }
  14321. texture.isReady = true;
  14322. // this.resetTextureCache();
  14323. scene._removePendingData(texture);
  14324. if (onLoad) {
  14325. onLoad();
  14326. }
  14327. };
  14328. this._loadFile(url, function (data) {
  14329. internalCallback(data);
  14330. }, undefined, scene.database, true, onerror);
  14331. return texture;
  14332. };
  14333. ;
  14334. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14335. if (compression === void 0) { compression = null; }
  14336. var internalFormat = this._getInternalFormat(format);
  14337. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14338. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14339. if (!this._doNotHandleContextLost) {
  14340. texture._bufferView = data;
  14341. texture.format = format;
  14342. texture.invertY = invertY;
  14343. texture._compression = compression;
  14344. }
  14345. if (texture.width % 4 !== 0) {
  14346. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14347. }
  14348. if (compression && data) {
  14349. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14350. }
  14351. else {
  14352. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14353. }
  14354. if (texture.generateMipMaps) {
  14355. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14356. }
  14357. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14358. // this.resetTextureCache();
  14359. texture.isReady = true;
  14360. };
  14361. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14362. if (compression === void 0) { compression = null; }
  14363. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14364. texture.baseWidth = width;
  14365. texture.baseHeight = height;
  14366. texture.baseDepth = depth;
  14367. texture.width = width;
  14368. texture.height = height;
  14369. texture.depth = depth;
  14370. texture.format = format;
  14371. texture.generateMipMaps = generateMipMaps;
  14372. texture.samplingMode = samplingMode;
  14373. texture.is3D = true;
  14374. if (!this._doNotHandleContextLost) {
  14375. texture._bufferView = data;
  14376. }
  14377. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14378. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14379. // Filters
  14380. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14381. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14382. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14383. if (generateMipMaps) {
  14384. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14385. }
  14386. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14387. this._internalTexturesCache.push(texture);
  14388. return texture;
  14389. };
  14390. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14391. var gl = this._gl;
  14392. if (!gl) {
  14393. return;
  14394. }
  14395. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14396. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14397. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14398. if (!noMipmap && !isCompressed) {
  14399. gl.generateMipmap(gl.TEXTURE_2D);
  14400. }
  14401. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14402. // this.resetTextureCache();
  14403. if (scene) {
  14404. scene._removePendingData(texture);
  14405. }
  14406. texture.onLoadedObservable.notifyObservers(texture);
  14407. texture.onLoadedObservable.clear();
  14408. };
  14409. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14410. var _this = this;
  14411. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14412. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14413. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14414. var gl = this._gl;
  14415. if (!gl) {
  14416. return;
  14417. }
  14418. if (!texture._webGLTexture) {
  14419. // this.resetTextureCache();
  14420. if (scene) {
  14421. scene._removePendingData(texture);
  14422. }
  14423. return;
  14424. }
  14425. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14426. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14427. texture.baseWidth = width;
  14428. texture.baseHeight = height;
  14429. texture.width = potWidth;
  14430. texture.height = potHeight;
  14431. texture.isReady = true;
  14432. if (processFunction(potWidth, potHeight, function () {
  14433. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14434. })) {
  14435. // Returning as texture needs extra async steps
  14436. return;
  14437. }
  14438. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14439. };
  14440. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14441. // Create new RGBA data container.
  14442. var rgbaData;
  14443. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14444. rgbaData = new Float32Array(width * height * 4);
  14445. }
  14446. else {
  14447. rgbaData = new Uint32Array(width * height * 4);
  14448. }
  14449. // Convert each pixel.
  14450. for (var x = 0; x < width; x++) {
  14451. for (var y = 0; y < height; y++) {
  14452. var index = (y * width + x) * 3;
  14453. var newIndex = (y * width + x) * 4;
  14454. // Map Old Value to new value.
  14455. rgbaData[newIndex + 0] = rgbData[index + 0];
  14456. rgbaData[newIndex + 1] = rgbData[index + 1];
  14457. rgbaData[newIndex + 2] = rgbData[index + 2];
  14458. // Add fully opaque alpha channel.
  14459. rgbaData[newIndex + 3] = 1;
  14460. }
  14461. }
  14462. return rgbaData;
  14463. };
  14464. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14465. var gl = this._gl;
  14466. if (texture._framebuffer) {
  14467. gl.deleteFramebuffer(texture._framebuffer);
  14468. texture._framebuffer = null;
  14469. }
  14470. if (texture._depthStencilBuffer) {
  14471. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14472. texture._depthStencilBuffer = null;
  14473. }
  14474. if (texture._MSAAFramebuffer) {
  14475. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14476. texture._MSAAFramebuffer = null;
  14477. }
  14478. if (texture._MSAARenderBuffer) {
  14479. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14480. texture._MSAARenderBuffer = null;
  14481. }
  14482. };
  14483. Engine.prototype._releaseTexture = function (texture) {
  14484. var gl = this._gl;
  14485. this._releaseFramebufferObjects(texture);
  14486. gl.deleteTexture(texture._webGLTexture);
  14487. // Unbind channels
  14488. this.unbindAllTextures();
  14489. var index = this._internalTexturesCache.indexOf(texture);
  14490. if (index !== -1) {
  14491. this._internalTexturesCache.splice(index, 1);
  14492. }
  14493. // Integrated fixed lod samplers.
  14494. if (texture._lodTextureHigh) {
  14495. texture._lodTextureHigh.dispose();
  14496. }
  14497. if (texture._lodTextureMid) {
  14498. texture._lodTextureMid.dispose();
  14499. }
  14500. if (texture._lodTextureLow) {
  14501. texture._lodTextureLow.dispose();
  14502. }
  14503. // Set output texture of post process to null if the texture has been released/disposed
  14504. this.scenes.forEach(function (scene) {
  14505. scene.postProcesses.forEach(function (postProcess) {
  14506. if (postProcess._outputTexture == texture) {
  14507. postProcess._outputTexture = null;
  14508. }
  14509. });
  14510. scene.cameras.forEach(function (camera) {
  14511. camera._postProcesses.forEach(function (postProcess) {
  14512. if (postProcess) {
  14513. if (postProcess._outputTexture == texture) {
  14514. postProcess._outputTexture = null;
  14515. }
  14516. }
  14517. });
  14518. });
  14519. });
  14520. };
  14521. Engine.prototype.setProgram = function (program) {
  14522. if (this._currentProgram !== program) {
  14523. this._gl.useProgram(program);
  14524. this._currentProgram = program;
  14525. }
  14526. };
  14527. Engine.prototype.bindSamplers = function (effect) {
  14528. this.setProgram(effect.getProgram());
  14529. var samplers = effect.getSamplers();
  14530. for (var index = 0; index < samplers.length; index++) {
  14531. var uniform = effect.getUniform(samplers[index]);
  14532. if (uniform) {
  14533. this._boundUniforms[index] = uniform;
  14534. }
  14535. }
  14536. this._currentEffect = null;
  14537. };
  14538. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14539. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14540. return;
  14541. }
  14542. // Remove
  14543. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14544. // Bind last to it
  14545. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14546. // Bind to dummy
  14547. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14548. };
  14549. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14550. if (!internalTexture) {
  14551. return -1;
  14552. }
  14553. internalTexture._initialSlot = channel;
  14554. if (this.disableTextureBindingOptimization) {
  14555. if (channel !== internalTexture._designatedSlot) {
  14556. this._textureCollisions.addCount(1, false);
  14557. }
  14558. }
  14559. else {
  14560. if (channel !== internalTexture._designatedSlot) {
  14561. if (internalTexture._designatedSlot > -1) {
  14562. return internalTexture._designatedSlot;
  14563. }
  14564. else {
  14565. // No slot for this texture, let's pick a new one (if we find a free slot)
  14566. if (this._nextFreeTextureSlots.length) {
  14567. return this._nextFreeTextureSlots[0];
  14568. }
  14569. // We need to recycle the oldest bound texture, sorry.
  14570. this._textureCollisions.addCount(1, false);
  14571. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14572. }
  14573. }
  14574. }
  14575. return channel;
  14576. };
  14577. Engine.prototype._linkTrackers = function (previous, next) {
  14578. previous.next = next;
  14579. next.previous = previous;
  14580. };
  14581. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14582. var currentSlot = internalTexture._designatedSlot;
  14583. if (currentSlot === -1) {
  14584. return -1;
  14585. }
  14586. internalTexture._designatedSlot = -1;
  14587. if (this.disableTextureBindingOptimization) {
  14588. return -1;
  14589. }
  14590. // Remove from bound list
  14591. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14592. // Free the slot
  14593. this._boundTexturesCache[currentSlot] = null;
  14594. this._nextFreeTextureSlots.push(currentSlot);
  14595. return currentSlot;
  14596. };
  14597. Engine.prototype._activateCurrentTexture = function () {
  14598. if (this._currentTextureChannel !== this._activeChannel) {
  14599. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14600. this._currentTextureChannel = this._activeChannel;
  14601. }
  14602. };
  14603. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14604. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14605. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14606. this._activeChannel = texture._designatedSlot;
  14607. }
  14608. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14609. var isTextureForRendering = texture && texture._initialSlot > -1;
  14610. if (currentTextureBound !== texture) {
  14611. if (currentTextureBound) {
  14612. this._removeDesignatedSlot(currentTextureBound);
  14613. }
  14614. this._activateCurrentTexture();
  14615. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14616. this._boundTexturesCache[this._activeChannel] = texture;
  14617. if (texture) {
  14618. if (!this.disableTextureBindingOptimization) {
  14619. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14620. if (slotIndex > -1) {
  14621. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14622. }
  14623. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14624. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14625. }
  14626. texture._designatedSlot = this._activeChannel;
  14627. }
  14628. }
  14629. else if (forTextureDataUpdate) {
  14630. this._activateCurrentTexture();
  14631. }
  14632. if (isTextureForRendering && !forTextureDataUpdate) {
  14633. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14634. }
  14635. };
  14636. Engine.prototype._bindTexture = function (channel, texture) {
  14637. if (channel < 0) {
  14638. return;
  14639. }
  14640. if (texture) {
  14641. channel = this._getCorrectTextureChannel(channel, texture);
  14642. }
  14643. this._activeChannel = channel;
  14644. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14645. };
  14646. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14647. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14648. };
  14649. /**
  14650. * Binds the output of the passed in post process to the texture channel specified
  14651. * @param channel The channel the texture should be bound to
  14652. * @param postProcess The post process which's output should be bound
  14653. */
  14654. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14655. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14656. };
  14657. Engine.prototype.unbindAllTextures = function () {
  14658. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14659. this._activeChannel = channel;
  14660. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14661. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14662. if (this.webGLVersion > 1) {
  14663. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14664. }
  14665. }
  14666. };
  14667. /**
  14668. * Sets a texture to the according uniform.
  14669. * @param channel The texture channel
  14670. * @param uniform The uniform to set
  14671. * @param texture The texture to apply
  14672. */
  14673. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14674. if (channel < 0) {
  14675. return;
  14676. }
  14677. if (uniform) {
  14678. this._boundUniforms[channel] = uniform;
  14679. }
  14680. this._setTexture(channel, texture);
  14681. };
  14682. /**
  14683. * Sets a depth stencil texture from a render target to the according uniform.
  14684. * @param channel The texture channel
  14685. * @param uniform The uniform to set
  14686. * @param texture The render target texture containing the depth stencil texture to apply
  14687. */
  14688. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14689. if (channel < 0) {
  14690. return;
  14691. }
  14692. if (uniform) {
  14693. this._boundUniforms[channel] = uniform;
  14694. }
  14695. if (!texture || !texture.depthStencilTexture) {
  14696. this._setTexture(channel, null);
  14697. }
  14698. else {
  14699. this._setTexture(channel, texture, false, true);
  14700. }
  14701. };
  14702. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14703. var uniform = this._boundUniforms[sourceSlot];
  14704. if (uniform._currentState === destination) {
  14705. return;
  14706. }
  14707. this._gl.uniform1i(uniform, destination);
  14708. uniform._currentState = destination;
  14709. };
  14710. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14711. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14712. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14713. // Not ready?
  14714. if (!texture) {
  14715. if (this._boundTexturesCache[channel] != null) {
  14716. this._activeChannel = channel;
  14717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14718. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14719. if (this.webGLVersion > 1) {
  14720. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14721. }
  14722. }
  14723. return false;
  14724. }
  14725. // Video
  14726. if (texture.video) {
  14727. this._activeChannel = channel;
  14728. texture.update();
  14729. }
  14730. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14731. texture.delayLoad();
  14732. return false;
  14733. }
  14734. var internalTexture;
  14735. if (depthStencilTexture) {
  14736. internalTexture = texture.depthStencilTexture;
  14737. }
  14738. else if (texture.isReady()) {
  14739. internalTexture = texture.getInternalTexture();
  14740. }
  14741. else if (texture.isCube) {
  14742. internalTexture = this.emptyCubeTexture;
  14743. }
  14744. else if (texture.is3D) {
  14745. internalTexture = this.emptyTexture3D;
  14746. }
  14747. else {
  14748. internalTexture = this.emptyTexture;
  14749. }
  14750. if (!isPartOfTextureArray) {
  14751. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14752. }
  14753. if (this._boundTexturesCache[channel] === internalTexture) {
  14754. this._moveBoundTextureOnTop(internalTexture);
  14755. if (!isPartOfTextureArray) {
  14756. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14757. }
  14758. return false;
  14759. }
  14760. this._activeChannel = channel;
  14761. if (internalTexture && internalTexture.is3D) {
  14762. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14763. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14764. internalTexture._cachedWrapU = texture.wrapU;
  14765. switch (texture.wrapU) {
  14766. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14767. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14768. break;
  14769. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14770. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14771. break;
  14772. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14773. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14774. break;
  14775. }
  14776. }
  14777. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14778. internalTexture._cachedWrapV = texture.wrapV;
  14779. switch (texture.wrapV) {
  14780. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14781. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14782. break;
  14783. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14784. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14785. break;
  14786. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14787. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14788. break;
  14789. }
  14790. }
  14791. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14792. internalTexture._cachedWrapR = texture.wrapR;
  14793. switch (texture.wrapR) {
  14794. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14795. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14796. break;
  14797. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14798. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14799. break;
  14800. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14801. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14802. break;
  14803. }
  14804. }
  14805. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14806. }
  14807. else if (internalTexture && internalTexture.isCube) {
  14808. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14809. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14810. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14811. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14812. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14813. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14815. }
  14816. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14817. }
  14818. else {
  14819. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14820. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14821. internalTexture._cachedWrapU = texture.wrapU;
  14822. switch (texture.wrapU) {
  14823. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14824. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14825. break;
  14826. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14827. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14828. break;
  14829. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14830. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14831. break;
  14832. }
  14833. }
  14834. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14835. internalTexture._cachedWrapV = texture.wrapV;
  14836. switch (texture.wrapV) {
  14837. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14839. break;
  14840. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14842. break;
  14843. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14844. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14845. break;
  14846. }
  14847. }
  14848. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14849. }
  14850. return true;
  14851. };
  14852. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14853. if (channel < 0 || !uniform) {
  14854. return;
  14855. }
  14856. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14857. this._textureUnits = new Int32Array(textures.length);
  14858. }
  14859. for (var i = 0; i < textures.length; i++) {
  14860. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14861. }
  14862. this._gl.uniform1iv(uniform, this._textureUnits);
  14863. for (var index = 0; index < textures.length; index++) {
  14864. this._setTexture(this._textureUnits[index], textures[index], true);
  14865. }
  14866. };
  14867. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14868. var internalTexture = texture.getInternalTexture();
  14869. if (!internalTexture) {
  14870. return;
  14871. }
  14872. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14873. var value = texture.anisotropicFilteringLevel;
  14874. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14875. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14876. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14877. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14878. }
  14879. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14880. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14881. internalTexture._cachedAnisotropicFilteringLevel = value;
  14882. }
  14883. };
  14884. Engine.prototype.readPixels = function (x, y, width, height) {
  14885. var data = new Uint8Array(height * width * 4);
  14886. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14887. return data;
  14888. };
  14889. /**
  14890. * Add an externaly attached data from its key.
  14891. * This method call will fail and return false, if such key already exists.
  14892. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14893. * @param key the unique key that identifies the data
  14894. * @param data the data object to associate to the key for this Engine instance
  14895. * @return true if no such key were already present and the data was added successfully, false otherwise
  14896. */
  14897. Engine.prototype.addExternalData = function (key, data) {
  14898. if (!this._externalData) {
  14899. this._externalData = new BABYLON.StringDictionary();
  14900. }
  14901. return this._externalData.add(key, data);
  14902. };
  14903. /**
  14904. * Get an externaly attached data from its key
  14905. * @param key the unique key that identifies the data
  14906. * @return the associated data, if present (can be null), or undefined if not present
  14907. */
  14908. Engine.prototype.getExternalData = function (key) {
  14909. if (!this._externalData) {
  14910. this._externalData = new BABYLON.StringDictionary();
  14911. }
  14912. return this._externalData.get(key);
  14913. };
  14914. /**
  14915. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14916. * @param key the unique key that identifies the data
  14917. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14918. * @return the associated data, can be null if the factory returned null.
  14919. */
  14920. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14921. if (!this._externalData) {
  14922. this._externalData = new BABYLON.StringDictionary();
  14923. }
  14924. return this._externalData.getOrAddWithFactory(key, factory);
  14925. };
  14926. /**
  14927. * Remove an externaly attached data from the Engine instance
  14928. * @param key the unique key that identifies the data
  14929. * @return true if the data was successfully removed, false if it doesn't exist
  14930. */
  14931. Engine.prototype.removeExternalData = function (key) {
  14932. if (!this._externalData) {
  14933. this._externalData = new BABYLON.StringDictionary();
  14934. }
  14935. return this._externalData.remove(key);
  14936. };
  14937. Engine.prototype.unbindAllAttributes = function () {
  14938. if (this._mustWipeVertexAttributes) {
  14939. this._mustWipeVertexAttributes = false;
  14940. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14941. this._gl.disableVertexAttribArray(i);
  14942. this._vertexAttribArraysEnabled[i] = false;
  14943. this._currentBufferPointers[i].active = false;
  14944. }
  14945. return;
  14946. }
  14947. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14948. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14949. continue;
  14950. }
  14951. this._gl.disableVertexAttribArray(i);
  14952. this._vertexAttribArraysEnabled[i] = false;
  14953. this._currentBufferPointers[i].active = false;
  14954. }
  14955. };
  14956. Engine.prototype.releaseEffects = function () {
  14957. for (var name in this._compiledEffects) {
  14958. this._deleteProgram(this._compiledEffects[name]._program);
  14959. }
  14960. this._compiledEffects = {};
  14961. };
  14962. // Dispose
  14963. Engine.prototype.dispose = function () {
  14964. this.hideLoadingUI();
  14965. this.stopRenderLoop();
  14966. // Release postProcesses
  14967. while (this.postProcesses.length) {
  14968. this.postProcesses[0].dispose();
  14969. }
  14970. // Empty texture
  14971. if (this._emptyTexture) {
  14972. this._releaseTexture(this._emptyTexture);
  14973. this._emptyTexture = null;
  14974. }
  14975. if (this._emptyCubeTexture) {
  14976. this._releaseTexture(this._emptyCubeTexture);
  14977. this._emptyCubeTexture = null;
  14978. }
  14979. // Rescale PP
  14980. if (this._rescalePostProcess) {
  14981. this._rescalePostProcess.dispose();
  14982. }
  14983. // Release scenes
  14984. while (this.scenes.length) {
  14985. this.scenes[0].dispose();
  14986. }
  14987. // Release audio engine
  14988. if (Engine.audioEngine) {
  14989. Engine.audioEngine.dispose();
  14990. }
  14991. // Release effects
  14992. this.releaseEffects();
  14993. // Unbind
  14994. this.unbindAllAttributes();
  14995. this._boundUniforms = [];
  14996. if (this._dummyFramebuffer) {
  14997. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14998. }
  14999. //WebVR
  15000. this.disableVR();
  15001. // Events
  15002. if (BABYLON.Tools.IsWindowObjectExist()) {
  15003. window.removeEventListener("blur", this._onBlur);
  15004. window.removeEventListener("focus", this._onFocus);
  15005. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15006. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15007. if (this._renderingCanvas) {
  15008. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15009. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15010. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15011. if (!this._doNotHandleContextLost) {
  15012. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15013. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15014. }
  15015. }
  15016. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15017. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15018. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15019. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15020. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15021. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15022. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15023. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15024. if (this._onVrDisplayConnect) {
  15025. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15026. if (this._onVrDisplayDisconnect) {
  15027. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15028. }
  15029. if (this._onVrDisplayPresentChange) {
  15030. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15031. }
  15032. this._onVrDisplayConnect = null;
  15033. this._onVrDisplayDisconnect = null;
  15034. }
  15035. }
  15036. // Remove from Instances
  15037. var index = Engine.Instances.indexOf(this);
  15038. if (index >= 0) {
  15039. Engine.Instances.splice(index, 1);
  15040. }
  15041. this._workingCanvas = null;
  15042. this._workingContext = null;
  15043. this._currentBufferPointers = [];
  15044. this._renderingCanvas = null;
  15045. this._currentProgram = null;
  15046. this._bindedRenderFunction = null;
  15047. this.onResizeObservable.clear();
  15048. this.onCanvasBlurObservable.clear();
  15049. this.onCanvasFocusObservable.clear();
  15050. this.onCanvasPointerOutObservable.clear();
  15051. this.onBeginFrameObservable.clear();
  15052. this.onEndFrameObservable.clear();
  15053. BABYLON.Effect.ResetCache();
  15054. // Abort active requests
  15055. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15056. var request = _a[_i];
  15057. request.abort();
  15058. }
  15059. };
  15060. // Loading screen
  15061. Engine.prototype.displayLoadingUI = function () {
  15062. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15063. return;
  15064. }
  15065. var loadingScreen = this.loadingScreen;
  15066. if (loadingScreen) {
  15067. loadingScreen.displayLoadingUI();
  15068. }
  15069. };
  15070. Engine.prototype.hideLoadingUI = function () {
  15071. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15072. return;
  15073. }
  15074. var loadingScreen = this.loadingScreen;
  15075. if (loadingScreen) {
  15076. loadingScreen.hideLoadingUI();
  15077. }
  15078. };
  15079. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15080. get: function () {
  15081. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15082. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15083. return this._loadingScreen;
  15084. },
  15085. set: function (loadingScreen) {
  15086. this._loadingScreen = loadingScreen;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15092. set: function (text) {
  15093. this.loadingScreen.loadingUIText = text;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15099. set: function (color) {
  15100. this.loadingScreen.loadingUIBackgroundColor = color;
  15101. },
  15102. enumerable: true,
  15103. configurable: true
  15104. });
  15105. Engine.prototype.attachContextLostEvent = function (callback) {
  15106. if (this._renderingCanvas) {
  15107. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15108. }
  15109. };
  15110. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15111. if (this._renderingCanvas) {
  15112. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15113. }
  15114. };
  15115. Engine.prototype.getVertexShaderSource = function (program) {
  15116. var shaders = this._gl.getAttachedShaders(program);
  15117. if (!shaders) {
  15118. return null;
  15119. }
  15120. return this._gl.getShaderSource(shaders[0]);
  15121. };
  15122. Engine.prototype.getFragmentShaderSource = function (program) {
  15123. var shaders = this._gl.getAttachedShaders(program);
  15124. if (!shaders) {
  15125. return null;
  15126. }
  15127. return this._gl.getShaderSource(shaders[1]);
  15128. };
  15129. Engine.prototype.getError = function () {
  15130. return this._gl.getError();
  15131. };
  15132. // FPS
  15133. Engine.prototype.getFps = function () {
  15134. return this._fps;
  15135. };
  15136. Engine.prototype.getDeltaTime = function () {
  15137. return this._deltaTime;
  15138. };
  15139. Engine.prototype._measureFps = function () {
  15140. this._performanceMonitor.sampleFrame();
  15141. this._fps = this._performanceMonitor.averageFPS;
  15142. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15143. };
  15144. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15145. if (faceIndex === void 0) { faceIndex = -1; }
  15146. var gl = this._gl;
  15147. if (!this._dummyFramebuffer) {
  15148. var dummy = gl.createFramebuffer();
  15149. if (!dummy) {
  15150. throw new Error("Unable to create dummy framebuffer");
  15151. }
  15152. this._dummyFramebuffer = dummy;
  15153. }
  15154. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15155. if (faceIndex > -1) {
  15156. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15157. }
  15158. else {
  15159. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15160. }
  15161. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15162. var buffer;
  15163. switch (readType) {
  15164. case gl.UNSIGNED_BYTE:
  15165. buffer = new Uint8Array(4 * width * height);
  15166. readType = gl.UNSIGNED_BYTE;
  15167. break;
  15168. default:
  15169. buffer = new Float32Array(4 * width * height);
  15170. readType = gl.FLOAT;
  15171. break;
  15172. }
  15173. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15174. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15175. return buffer;
  15176. };
  15177. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15178. if (this._webGLVersion > 1) {
  15179. return this._caps.colorBufferFloat;
  15180. }
  15181. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15182. };
  15183. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15184. if (this._webGLVersion > 1) {
  15185. return this._caps.colorBufferFloat;
  15186. }
  15187. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15188. };
  15189. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15190. Engine.prototype._canRenderToFramebuffer = function (type) {
  15191. var gl = this._gl;
  15192. //clear existing errors
  15193. while (gl.getError() !== gl.NO_ERROR) { }
  15194. var successful = true;
  15195. var texture = gl.createTexture();
  15196. gl.bindTexture(gl.TEXTURE_2D, texture);
  15197. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15200. var fb = gl.createFramebuffer();
  15201. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15203. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15204. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15205. successful = successful && (gl.getError() === gl.NO_ERROR);
  15206. //try render by clearing frame buffer's color buffer
  15207. if (successful) {
  15208. gl.clear(gl.COLOR_BUFFER_BIT);
  15209. successful = successful && (gl.getError() === gl.NO_ERROR);
  15210. }
  15211. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15212. if (successful) {
  15213. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15214. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15215. var readFormat = gl.RGBA;
  15216. var readType = gl.UNSIGNED_BYTE;
  15217. var buffer = new Uint8Array(4);
  15218. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15219. successful = successful && (gl.getError() === gl.NO_ERROR);
  15220. }
  15221. //clean up
  15222. gl.deleteTexture(texture);
  15223. gl.deleteFramebuffer(fb);
  15224. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15225. //clear accumulated errors
  15226. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15227. return successful;
  15228. };
  15229. Engine.prototype._getWebGLTextureType = function (type) {
  15230. if (type === Engine.TEXTURETYPE_FLOAT) {
  15231. return this._gl.FLOAT;
  15232. }
  15233. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15234. // Add Half Float Constant.
  15235. return this._gl.HALF_FLOAT_OES;
  15236. }
  15237. return this._gl.UNSIGNED_BYTE;
  15238. };
  15239. ;
  15240. Engine.prototype._getInternalFormat = function (format) {
  15241. var internalFormat = this._gl.RGBA;
  15242. switch (format) {
  15243. case Engine.TEXTUREFORMAT_ALPHA:
  15244. internalFormat = this._gl.ALPHA;
  15245. break;
  15246. case Engine.TEXTUREFORMAT_LUMINANCE:
  15247. internalFormat = this._gl.LUMINANCE;
  15248. break;
  15249. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15250. internalFormat = this._gl.LUMINANCE_ALPHA;
  15251. break;
  15252. case Engine.TEXTUREFORMAT_RGB:
  15253. case Engine.TEXTUREFORMAT_RGB32F:
  15254. internalFormat = this._gl.RGB;
  15255. break;
  15256. case Engine.TEXTUREFORMAT_RGBA:
  15257. case Engine.TEXTUREFORMAT_RGBA32F:
  15258. internalFormat = this._gl.RGBA;
  15259. break;
  15260. case Engine.TEXTUREFORMAT_R32F:
  15261. internalFormat = this._gl.RED;
  15262. break;
  15263. case Engine.TEXTUREFORMAT_RG32F:
  15264. internalFormat = this._gl.RG;
  15265. break;
  15266. }
  15267. return internalFormat;
  15268. };
  15269. /** @ignore */
  15270. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15271. if (this._webGLVersion === 1) {
  15272. if (format) {
  15273. switch (format) {
  15274. case Engine.TEXTUREFORMAT_LUMINANCE:
  15275. return this._gl.LUMINANCE;
  15276. }
  15277. }
  15278. return this._gl.RGBA;
  15279. }
  15280. if (type === Engine.TEXTURETYPE_FLOAT) {
  15281. if (format) {
  15282. switch (format) {
  15283. case Engine.TEXTUREFORMAT_R32F:
  15284. return this._gl.R32F;
  15285. case Engine.TEXTUREFORMAT_RG32F:
  15286. return this._gl.RG32F;
  15287. case Engine.TEXTUREFORMAT_RGB32F:
  15288. return this._gl.RGB32F;
  15289. }
  15290. }
  15291. return this._gl.RGBA32F;
  15292. }
  15293. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15294. return this._gl.RGBA16F;
  15295. }
  15296. if (format) {
  15297. switch (format) {
  15298. case Engine.TEXTUREFORMAT_LUMINANCE:
  15299. return this._gl.LUMINANCE;
  15300. }
  15301. }
  15302. return this._gl.RGBA;
  15303. };
  15304. ;
  15305. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15306. if (type === Engine.TEXTURETYPE_FLOAT) {
  15307. return this._gl.RGBA32F;
  15308. }
  15309. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15310. return this._gl.RGBA16F;
  15311. }
  15312. return this._gl.RGBA8;
  15313. };
  15314. ;
  15315. Engine.prototype.createQuery = function () {
  15316. return this._gl.createQuery();
  15317. };
  15318. Engine.prototype.deleteQuery = function (query) {
  15319. this._gl.deleteQuery(query);
  15320. return this;
  15321. };
  15322. Engine.prototype.isQueryResultAvailable = function (query) {
  15323. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15324. };
  15325. Engine.prototype.getQueryResult = function (query) {
  15326. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15327. };
  15328. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15329. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15330. this._gl.beginQuery(glAlgorithm, query);
  15331. return this;
  15332. };
  15333. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15334. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15335. this._gl.endQuery(glAlgorithm);
  15336. return this;
  15337. };
  15338. /* Time queries */
  15339. Engine.prototype._createTimeQuery = function () {
  15340. var timerQuery = this._caps.timerQuery;
  15341. if (timerQuery.createQueryEXT) {
  15342. return timerQuery.createQueryEXT();
  15343. }
  15344. return this.createQuery();
  15345. };
  15346. Engine.prototype._deleteTimeQuery = function (query) {
  15347. var timerQuery = this._caps.timerQuery;
  15348. if (timerQuery.deleteQueryEXT) {
  15349. timerQuery.deleteQueryEXT(query);
  15350. return;
  15351. }
  15352. this.deleteQuery(query);
  15353. };
  15354. Engine.prototype._getTimeQueryResult = function (query) {
  15355. var timerQuery = this._caps.timerQuery;
  15356. if (timerQuery.getQueryObjectEXT) {
  15357. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15358. }
  15359. return this.getQueryResult(query);
  15360. };
  15361. Engine.prototype._getTimeQueryAvailability = function (query) {
  15362. var timerQuery = this._caps.timerQuery;
  15363. if (timerQuery.getQueryObjectEXT) {
  15364. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15365. }
  15366. return this.isQueryResultAvailable(query);
  15367. };
  15368. Engine.prototype.startTimeQuery = function () {
  15369. var timerQuery = this._caps.timerQuery;
  15370. if (!timerQuery) {
  15371. return null;
  15372. }
  15373. var token = new BABYLON._TimeToken();
  15374. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15375. if (this._caps.canUseTimestampForTimerQuery) {
  15376. token._startTimeQuery = this._createTimeQuery();
  15377. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15378. }
  15379. else {
  15380. if (this._currentNonTimestampToken) {
  15381. return this._currentNonTimestampToken;
  15382. }
  15383. token._timeElapsedQuery = this._createTimeQuery();
  15384. if (timerQuery.beginQueryEXT) {
  15385. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15386. }
  15387. else {
  15388. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15389. }
  15390. this._currentNonTimestampToken = token;
  15391. }
  15392. return token;
  15393. };
  15394. Engine.prototype.endTimeQuery = function (token) {
  15395. var timerQuery = this._caps.timerQuery;
  15396. if (!timerQuery || !token) {
  15397. return -1;
  15398. }
  15399. if (this._caps.canUseTimestampForTimerQuery) {
  15400. if (!token._startTimeQuery) {
  15401. return -1;
  15402. }
  15403. if (!token._endTimeQuery) {
  15404. token._endTimeQuery = this._createTimeQuery();
  15405. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15406. }
  15407. }
  15408. else if (!token._timeElapsedQueryEnded) {
  15409. if (!token._timeElapsedQuery) {
  15410. return -1;
  15411. }
  15412. if (timerQuery.endQueryEXT) {
  15413. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15414. }
  15415. else {
  15416. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15417. }
  15418. token._timeElapsedQueryEnded = true;
  15419. }
  15420. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15421. var available = false;
  15422. if (token._endTimeQuery) {
  15423. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15424. }
  15425. else if (token._timeElapsedQuery) {
  15426. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15427. }
  15428. if (available && !disjoint) {
  15429. var result = 0;
  15430. if (this._caps.canUseTimestampForTimerQuery) {
  15431. if (!token._startTimeQuery || !token._endTimeQuery) {
  15432. return -1;
  15433. }
  15434. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15435. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15436. result = timeEnd - timeStart;
  15437. this._deleteTimeQuery(token._startTimeQuery);
  15438. this._deleteTimeQuery(token._endTimeQuery);
  15439. token._startTimeQuery = null;
  15440. token._endTimeQuery = null;
  15441. }
  15442. else {
  15443. if (!token._timeElapsedQuery) {
  15444. return -1;
  15445. }
  15446. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15447. this._deleteTimeQuery(token._timeElapsedQuery);
  15448. token._timeElapsedQuery = null;
  15449. token._timeElapsedQueryEnded = false;
  15450. this._currentNonTimestampToken = null;
  15451. }
  15452. return result;
  15453. }
  15454. return -1;
  15455. };
  15456. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15457. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15458. };
  15459. // Transform feedback
  15460. Engine.prototype.createTransformFeedback = function () {
  15461. return this._gl.createTransformFeedback();
  15462. };
  15463. Engine.prototype.deleteTransformFeedback = function (value) {
  15464. this._gl.deleteTransformFeedback(value);
  15465. };
  15466. Engine.prototype.bindTransformFeedback = function (value) {
  15467. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15468. };
  15469. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15470. if (usePoints === void 0) { usePoints = true; }
  15471. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15472. };
  15473. Engine.prototype.endTransformFeedback = function () {
  15474. this._gl.endTransformFeedback();
  15475. };
  15476. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15477. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15478. };
  15479. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15480. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15481. };
  15482. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15483. var _this = this;
  15484. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15485. this._activeRequests.push(request);
  15486. request.onCompleteObservable.add(function (request) {
  15487. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15488. });
  15489. return request;
  15490. };
  15491. /** @ignore */
  15492. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15493. var _this = this;
  15494. return new Promise(function (resolve, reject) {
  15495. _this._loadFile(url, function (data) {
  15496. resolve(data);
  15497. }, undefined, database, useArrayBuffer, function (request, exception) {
  15498. reject(exception);
  15499. });
  15500. });
  15501. };
  15502. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15503. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15504. var onload = function (data) {
  15505. loadedFiles[index] = data;
  15506. loadedFiles._internalCount++;
  15507. if (loadedFiles._internalCount === 6) {
  15508. onfinish(loadedFiles);
  15509. }
  15510. };
  15511. var onerror = function (request, exception) {
  15512. if (onErrorCallBack && request) {
  15513. onErrorCallBack(request.status + " " + request.statusText, exception);
  15514. }
  15515. };
  15516. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15517. };
  15518. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15519. if (onError === void 0) { onError = null; }
  15520. var loadedFiles = [];
  15521. loadedFiles._internalCount = 0;
  15522. for (var index = 0; index < 6; index++) {
  15523. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15524. }
  15525. };
  15526. // Statics
  15527. Engine.isSupported = function () {
  15528. try {
  15529. var tempcanvas = document.createElement("canvas");
  15530. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15531. return gl != null && !!window.WebGLRenderingContext;
  15532. }
  15533. catch (e) {
  15534. return false;
  15535. }
  15536. };
  15537. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15538. Engine.ExceptionList = [
  15539. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15540. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15541. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15542. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15543. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15544. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15545. ];
  15546. Engine.Instances = new Array();
  15547. // Const statics
  15548. Engine._ALPHA_DISABLE = 0;
  15549. Engine._ALPHA_ADD = 1;
  15550. Engine._ALPHA_COMBINE = 2;
  15551. Engine._ALPHA_SUBTRACT = 3;
  15552. Engine._ALPHA_MULTIPLY = 4;
  15553. Engine._ALPHA_MAXIMIZED = 5;
  15554. Engine._ALPHA_ONEONE = 6;
  15555. Engine._ALPHA_PREMULTIPLIED = 7;
  15556. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15557. Engine._ALPHA_INTERPOLATE = 9;
  15558. Engine._ALPHA_SCREENMODE = 10;
  15559. Engine._DELAYLOADSTATE_NONE = 0;
  15560. Engine._DELAYLOADSTATE_LOADED = 1;
  15561. Engine._DELAYLOADSTATE_LOADING = 2;
  15562. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15563. Engine._TEXTUREFORMAT_ALPHA = 0;
  15564. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15565. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15566. Engine._TEXTUREFORMAT_RGB = 4;
  15567. Engine._TEXTUREFORMAT_RGBA = 5;
  15568. Engine._TEXTUREFORMAT_R32F = 6;
  15569. Engine._TEXTUREFORMAT_RG32F = 7;
  15570. Engine._TEXTUREFORMAT_RGB32F = 8;
  15571. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15572. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15573. Engine._TEXTURETYPE_FLOAT = 1;
  15574. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15575. // Depht or Stencil test Constants.
  15576. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15577. 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.
  15578. 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.
  15579. 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.
  15580. 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.
  15581. 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.
  15582. 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.
  15583. 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.
  15584. // Stencil Actions Constants.
  15585. Engine._KEEP = 0x1E00;
  15586. Engine._REPLACE = 0x1E01;
  15587. Engine._INCR = 0x1E02;
  15588. Engine._DECR = 0x1E03;
  15589. Engine._INVERT = 0x150A;
  15590. Engine._INCR_WRAP = 0x8507;
  15591. Engine._DECR_WRAP = 0x8508;
  15592. // Texture rescaling mode
  15593. Engine._SCALEMODE_FLOOR = 1;
  15594. Engine._SCALEMODE_NEAREST = 2;
  15595. Engine._SCALEMODE_CEILING = 3;
  15596. // Updatable statics so stick with vars here
  15597. Engine.CollisionsEpsilon = 0.001;
  15598. Engine.CodeRepository = "src/";
  15599. Engine.ShadersRepository = "src/Shaders/";
  15600. return Engine;
  15601. }());
  15602. BABYLON.Engine = Engine;
  15603. })(BABYLON || (BABYLON = {}));
  15604. //# sourceMappingURL=babylon.engine.js.map
  15605. "use strict";
  15606. var BABYLON;
  15607. (function (BABYLON) {
  15608. /**
  15609. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15610. */
  15611. var Node = /** @class */ (function () {
  15612. /**
  15613. * Creates a new Node
  15614. * @param {string} name - the name and id to be given to this node
  15615. * @param {BABYLON.Scene} the scene this node will be added to
  15616. */
  15617. function Node(name, scene) {
  15618. if (scene === void 0) { scene = null; }
  15619. /**
  15620. * Gets or sets a string used to store user defined state for the node
  15621. */
  15622. this.state = "";
  15623. /**
  15624. * Gets or sets an object used to store user defined information for the node
  15625. */
  15626. this.metadata = null;
  15627. /**
  15628. * Gets or sets a boolean used to define if the node must be serialized
  15629. */
  15630. this.doNotSerialize = false;
  15631. /** @ignore */
  15632. this._isDisposed = false;
  15633. /**
  15634. * Gets a list of {BABYLON.Animation} associated with the node
  15635. */
  15636. this.animations = new Array();
  15637. this._ranges = {};
  15638. this._isEnabled = true;
  15639. this._isReady = true;
  15640. /** @ignore */
  15641. this._currentRenderId = -1;
  15642. this._parentRenderId = -1;
  15643. this._childRenderId = -1;
  15644. this._animationPropertiesOverride = null;
  15645. /**
  15646. * An event triggered when the mesh is disposed
  15647. * @type {BABYLON.Observable}
  15648. */
  15649. this.onDisposeObservable = new BABYLON.Observable();
  15650. // Behaviors
  15651. this._behaviors = new Array();
  15652. this.name = name;
  15653. this.id = name;
  15654. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15655. this.uniqueId = this._scene.getUniqueId();
  15656. this._initCache();
  15657. }
  15658. /**
  15659. * Gets a boolean indicating if the node has been disposed
  15660. * @returns true if the node was disposed
  15661. */
  15662. Node.prototype.isDisposed = function () {
  15663. return this._isDisposed;
  15664. };
  15665. Object.defineProperty(Node.prototype, "parent", {
  15666. get: function () {
  15667. return this._parentNode;
  15668. },
  15669. /**
  15670. * Gets or sets the parent of the node
  15671. */
  15672. set: function (parent) {
  15673. if (this._parentNode === parent) {
  15674. return;
  15675. }
  15676. // Remove self from list of children of parent
  15677. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15678. var index = this._parentNode._children.indexOf(this);
  15679. if (index !== -1) {
  15680. this._parentNode._children.splice(index, 1);
  15681. }
  15682. }
  15683. // Store new parent
  15684. this._parentNode = parent;
  15685. // Add as child to new parent
  15686. if (this._parentNode) {
  15687. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15688. this._parentNode._children = new Array();
  15689. }
  15690. this._parentNode._children.push(this);
  15691. }
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15697. /**
  15698. * Gets or sets the animation properties override
  15699. */
  15700. get: function () {
  15701. return this._animationPropertiesOverride;
  15702. },
  15703. set: function (value) {
  15704. this._animationPropertiesOverride = value;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. /**
  15710. * Gets a string idenfifying the name of the class
  15711. * @returns "Node" string
  15712. */
  15713. Node.prototype.getClassName = function () {
  15714. return "Node";
  15715. };
  15716. Object.defineProperty(Node.prototype, "onDispose", {
  15717. /**
  15718. * Sets a callback that will be raised when the node will be disposed
  15719. */
  15720. set: function (callback) {
  15721. if (this._onDisposeObserver) {
  15722. this.onDisposeObservable.remove(this._onDisposeObserver);
  15723. }
  15724. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15725. },
  15726. enumerable: true,
  15727. configurable: true
  15728. });
  15729. /**
  15730. * Gets the scene of the node
  15731. * @returns a {BABYLON.Scene}
  15732. */
  15733. Node.prototype.getScene = function () {
  15734. return this._scene;
  15735. };
  15736. /**
  15737. * Gets the engine of the node
  15738. * @returns a {BABYLON.Engine}
  15739. */
  15740. Node.prototype.getEngine = function () {
  15741. return this._scene.getEngine();
  15742. };
  15743. /**
  15744. * Attach a behavior to the node
  15745. * @see http://doc.babylonjs.com/features/behaviour
  15746. * @param behavior defines the behavior to attach
  15747. * @returns the current Node
  15748. */
  15749. Node.prototype.addBehavior = function (behavior) {
  15750. var _this = this;
  15751. var index = this._behaviors.indexOf(behavior);
  15752. if (index !== -1) {
  15753. return this;
  15754. }
  15755. behavior.init();
  15756. if (this._scene.isLoading) {
  15757. // We defer the attach when the scene will be loaded
  15758. var observer = this._scene.onDataLoadedObservable.add(function () {
  15759. behavior.attach(_this);
  15760. setTimeout(function () {
  15761. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15762. _this._scene.onDataLoadedObservable.remove(observer);
  15763. }, 0);
  15764. });
  15765. }
  15766. else {
  15767. behavior.attach(this);
  15768. }
  15769. this._behaviors.push(behavior);
  15770. return this;
  15771. };
  15772. /**
  15773. * Remove an attached behavior
  15774. * @see http://doc.babylonjs.com/features/behaviour
  15775. * @param behavior defines the behavior to attach
  15776. * @returns the current Node
  15777. */
  15778. Node.prototype.removeBehavior = function (behavior) {
  15779. var index = this._behaviors.indexOf(behavior);
  15780. if (index === -1) {
  15781. return this;
  15782. }
  15783. this._behaviors[index].detach();
  15784. this._behaviors.splice(index, 1);
  15785. return this;
  15786. };
  15787. Object.defineProperty(Node.prototype, "behaviors", {
  15788. /**
  15789. * Gets the list of attached behaviors
  15790. * @see http://doc.babylonjs.com/features/behaviour
  15791. */
  15792. get: function () {
  15793. return this._behaviors;
  15794. },
  15795. enumerable: true,
  15796. configurable: true
  15797. });
  15798. /**
  15799. * Gets an attached behavior by name
  15800. * @param name defines the name of the behavior to look for
  15801. * @see http://doc.babylonjs.com/features/behaviour
  15802. * @returns null if behavior was not found else the requested behavior
  15803. */
  15804. Node.prototype.getBehaviorByName = function (name) {
  15805. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15806. var behavior = _a[_i];
  15807. if (behavior.name === name) {
  15808. return behavior;
  15809. }
  15810. }
  15811. return null;
  15812. };
  15813. /**
  15814. * Returns the world matrix of the node
  15815. * @returns a matrix containing the node's world matrix
  15816. */
  15817. Node.prototype.getWorldMatrix = function () {
  15818. return BABYLON.Matrix.Identity();
  15819. };
  15820. // override it in derived class if you add new variables to the cache
  15821. // and call the parent class method
  15822. /** @ignore */
  15823. Node.prototype._initCache = function () {
  15824. this._cache = {};
  15825. this._cache.parent = undefined;
  15826. };
  15827. /** @ignore */
  15828. Node.prototype.updateCache = function (force) {
  15829. if (!force && this.isSynchronized())
  15830. return;
  15831. this._cache.parent = this.parent;
  15832. this._updateCache();
  15833. };
  15834. // override it in derived class if you add new variables to the cache
  15835. // and call the parent class method if !ignoreParentClass
  15836. /** @ignore */
  15837. Node.prototype._updateCache = function (ignoreParentClass) {
  15838. };
  15839. // override it in derived class if you add new variables to the cache
  15840. /** @ignore */
  15841. Node.prototype._isSynchronized = function () {
  15842. return true;
  15843. };
  15844. /** @ignore */
  15845. Node.prototype._markSyncedWithParent = function () {
  15846. if (this.parent) {
  15847. this._parentRenderId = this.parent._childRenderId;
  15848. }
  15849. };
  15850. /** @ignore */
  15851. Node.prototype.isSynchronizedWithParent = function () {
  15852. if (!this.parent) {
  15853. return true;
  15854. }
  15855. if (this._parentRenderId !== this.parent._childRenderId) {
  15856. return false;
  15857. }
  15858. return this.parent.isSynchronized();
  15859. };
  15860. /** @ignore */
  15861. Node.prototype.isSynchronized = function (updateCache) {
  15862. var check = this.hasNewParent();
  15863. check = check || !this.isSynchronizedWithParent();
  15864. check = check || !this._isSynchronized();
  15865. if (updateCache)
  15866. this.updateCache(true);
  15867. return !check;
  15868. };
  15869. /** @ignore */
  15870. Node.prototype.hasNewParent = function (update) {
  15871. if (this._cache.parent === this.parent)
  15872. return false;
  15873. if (update)
  15874. this._cache.parent = this.parent;
  15875. return true;
  15876. };
  15877. /**
  15878. * Is this node ready to be used/rendered
  15879. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15880. * @return true if the node is ready
  15881. */
  15882. Node.prototype.isReady = function (completeCheck) {
  15883. if (completeCheck === void 0) { completeCheck = false; }
  15884. return this._isReady;
  15885. };
  15886. /**
  15887. * Is this node enabled?
  15888. * 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
  15889. * @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
  15890. * @return whether this node (and its parent) is enabled
  15891. */
  15892. Node.prototype.isEnabled = function (checkAncestors) {
  15893. if (checkAncestors === void 0) { checkAncestors = true; }
  15894. if (checkAncestors === false) {
  15895. return this._isEnabled;
  15896. }
  15897. if (this._isEnabled === false) {
  15898. return false;
  15899. }
  15900. if (this.parent !== undefined && this.parent !== null) {
  15901. return this.parent.isEnabled(checkAncestors);
  15902. }
  15903. return true;
  15904. };
  15905. /**
  15906. * Set the enabled state of this node
  15907. * @param value defines the new enabled state
  15908. */
  15909. Node.prototype.setEnabled = function (value) {
  15910. this._isEnabled = value;
  15911. };
  15912. /**
  15913. * Is this node a descendant of the given node?
  15914. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15915. * @param ancestor defines the parent node to inspect
  15916. * @returns a boolean indicating if this node is a descendant of the given node
  15917. */
  15918. Node.prototype.isDescendantOf = function (ancestor) {
  15919. if (this.parent) {
  15920. if (this.parent === ancestor) {
  15921. return true;
  15922. }
  15923. return this.parent.isDescendantOf(ancestor);
  15924. }
  15925. return false;
  15926. };
  15927. /** @ignore */
  15928. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15929. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15930. if (!this._children) {
  15931. return;
  15932. }
  15933. for (var index = 0; index < this._children.length; index++) {
  15934. var item = this._children[index];
  15935. if (!predicate || predicate(item)) {
  15936. results.push(item);
  15937. }
  15938. if (!directDescendantsOnly) {
  15939. item._getDescendants(results, false, predicate);
  15940. }
  15941. }
  15942. };
  15943. /**
  15944. * Will return all nodes that have this node as ascendant
  15945. * @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
  15946. * @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
  15947. * @return all children nodes of all types
  15948. */
  15949. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15950. var results = new Array();
  15951. this._getDescendants(results, directDescendantsOnly, predicate);
  15952. return results;
  15953. };
  15954. /**
  15955. * Get all child-meshes of this node
  15956. * @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
  15957. * @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
  15958. * @returns an array of {BABYLON.AbstractMesh}
  15959. */
  15960. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15961. var results = [];
  15962. this._getDescendants(results, directDescendantsOnly, function (node) {
  15963. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15964. });
  15965. return results;
  15966. };
  15967. /**
  15968. * Get all child-transformNodes of this node
  15969. * @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
  15970. * @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
  15971. * @returns an array of {BABYLON.TransformNode}
  15972. */
  15973. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15974. var results = [];
  15975. this._getDescendants(results, directDescendantsOnly, function (node) {
  15976. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15977. });
  15978. return results;
  15979. };
  15980. /**
  15981. * Get all direct children of this node
  15982. * @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
  15983. * @returns an array of {BABYLON.Node}
  15984. */
  15985. Node.prototype.getChildren = function (predicate) {
  15986. return this.getDescendants(true, predicate);
  15987. };
  15988. /** @ignore */
  15989. Node.prototype._setReady = function (state) {
  15990. if (state === this._isReady) {
  15991. return;
  15992. }
  15993. if (!state) {
  15994. this._isReady = false;
  15995. return;
  15996. }
  15997. if (this.onReady) {
  15998. this.onReady(this);
  15999. }
  16000. this._isReady = true;
  16001. };
  16002. /**
  16003. * Get an animation by name
  16004. * @param name defines the name of the animation to look for
  16005. * @returns null if not found else the requested animation
  16006. */
  16007. Node.prototype.getAnimationByName = function (name) {
  16008. for (var i = 0; i < this.animations.length; i++) {
  16009. var animation = this.animations[i];
  16010. if (animation.name === name) {
  16011. return animation;
  16012. }
  16013. }
  16014. return null;
  16015. };
  16016. /**
  16017. * Creates an animation range for this node
  16018. * @param name defines the name of the range
  16019. * @param from defines the starting key
  16020. * @param to defines the end key
  16021. */
  16022. Node.prototype.createAnimationRange = function (name, from, to) {
  16023. // check name not already in use
  16024. if (!this._ranges[name]) {
  16025. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16026. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16027. if (this.animations[i]) {
  16028. this.animations[i].createRange(name, from, to);
  16029. }
  16030. }
  16031. }
  16032. };
  16033. /**
  16034. * Delete a specific animation range
  16035. * @param name defines the name of the range to delete
  16036. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16037. */
  16038. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16039. if (deleteFrames === void 0) { deleteFrames = true; }
  16040. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16041. if (this.animations[i]) {
  16042. this.animations[i].deleteRange(name, deleteFrames);
  16043. }
  16044. }
  16045. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16046. };
  16047. /**
  16048. * Get an animation range by name
  16049. * @param name defines the name of the animation range to look for
  16050. * @returns null if not found else the requested animation range
  16051. */
  16052. Node.prototype.getAnimationRange = function (name) {
  16053. return this._ranges[name];
  16054. };
  16055. /**
  16056. * Will start the animation sequence
  16057. * @param name defines the range frames for animation sequence
  16058. * @param loop defines if the animation should loop (false by default)
  16059. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16060. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16061. * @returns the object created for this animation. If range does not exist, it will return null
  16062. */
  16063. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16064. var range = this.getAnimationRange(name);
  16065. if (!range) {
  16066. return null;
  16067. }
  16068. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16069. };
  16070. /**
  16071. * Serialize animation ranges into a JSON compatible object
  16072. * @returns serialization object
  16073. */
  16074. Node.prototype.serializeAnimationRanges = function () {
  16075. var serializationRanges = [];
  16076. for (var name in this._ranges) {
  16077. var localRange = this._ranges[name];
  16078. if (!localRange) {
  16079. continue;
  16080. }
  16081. var range = {};
  16082. range.name = name;
  16083. range.from = localRange.from;
  16084. range.to = localRange.to;
  16085. serializationRanges.push(range);
  16086. }
  16087. return serializationRanges;
  16088. };
  16089. /**
  16090. * Computes the world matrix of the node
  16091. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16092. * @returns the world matrix
  16093. */
  16094. Node.prototype.computeWorldMatrix = function (force) {
  16095. return BABYLON.Matrix.Identity();
  16096. };
  16097. /**
  16098. * Releases resources associated with this node.
  16099. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16100. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16101. */
  16102. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16103. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16104. if (!doNotRecurse) {
  16105. var nodes = this.getDescendants(true);
  16106. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16107. var node = nodes_1[_i];
  16108. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16109. }
  16110. }
  16111. else {
  16112. var transformNodes = this.getChildTransformNodes(true);
  16113. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16114. var transformNode = transformNodes_1[_a];
  16115. transformNode.parent = null;
  16116. transformNode.computeWorldMatrix(true);
  16117. }
  16118. }
  16119. this.parent = null;
  16120. // Callback
  16121. this.onDisposeObservable.notifyObservers(this);
  16122. this.onDisposeObservable.clear();
  16123. // Behaviors
  16124. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16125. var behavior = _c[_b];
  16126. behavior.detach();
  16127. }
  16128. this._behaviors = [];
  16129. this._isDisposed = true;
  16130. };
  16131. /**
  16132. * Parse animation range data from a serialization object and store them into a given node
  16133. * @param node defines where to store the animation ranges
  16134. * @param parsedNode defines the serialization object to read data from
  16135. * @param scene defines the hosting scene
  16136. */
  16137. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16138. if (parsedNode.ranges) {
  16139. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16140. var data = parsedNode.ranges[index];
  16141. node.createAnimationRange(data.name, data.from, data.to);
  16142. }
  16143. }
  16144. };
  16145. __decorate([
  16146. BABYLON.serialize()
  16147. ], Node.prototype, "name", void 0);
  16148. __decorate([
  16149. BABYLON.serialize()
  16150. ], Node.prototype, "id", void 0);
  16151. __decorate([
  16152. BABYLON.serialize()
  16153. ], Node.prototype, "uniqueId", void 0);
  16154. __decorate([
  16155. BABYLON.serialize()
  16156. ], Node.prototype, "state", void 0);
  16157. __decorate([
  16158. BABYLON.serialize()
  16159. ], Node.prototype, "metadata", void 0);
  16160. return Node;
  16161. }());
  16162. BABYLON.Node = Node;
  16163. })(BABYLON || (BABYLON = {}));
  16164. //# sourceMappingURL=babylon.node.js.map
  16165. "use strict";
  16166. var BABYLON;
  16167. (function (BABYLON) {
  16168. var BoundingSphere = /** @class */ (function () {
  16169. function BoundingSphere(minimum, maximum) {
  16170. this.minimum = minimum;
  16171. this.maximum = maximum;
  16172. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16173. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16174. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16175. this.radius = distance * 0.5;
  16176. this.centerWorld = BABYLON.Vector3.Zero();
  16177. this._update(BABYLON.Matrix.Identity());
  16178. }
  16179. // Methods
  16180. BoundingSphere.prototype._update = function (world) {
  16181. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16182. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16183. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16184. };
  16185. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16186. for (var i = 0; i < 6; i++) {
  16187. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16188. return false;
  16189. }
  16190. return true;
  16191. };
  16192. BoundingSphere.prototype.intersectsPoint = function (point) {
  16193. var x = this.centerWorld.x - point.x;
  16194. var y = this.centerWorld.y - point.y;
  16195. var z = this.centerWorld.z - point.z;
  16196. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16197. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16198. return false;
  16199. return true;
  16200. };
  16201. // Statics
  16202. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16203. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16204. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16205. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16206. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16207. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16208. return false;
  16209. return true;
  16210. };
  16211. return BoundingSphere;
  16212. }());
  16213. BABYLON.BoundingSphere = BoundingSphere;
  16214. })(BABYLON || (BABYLON = {}));
  16215. //# sourceMappingURL=babylon.boundingSphere.js.map
  16216. "use strict";
  16217. var BABYLON;
  16218. (function (BABYLON) {
  16219. var BoundingBox = /** @class */ (function () {
  16220. function BoundingBox(minimum, maximum) {
  16221. this.minimum = minimum;
  16222. this.maximum = maximum;
  16223. this.vectors = new Array();
  16224. this.vectorsWorld = new Array();
  16225. // Bounding vectors
  16226. this.vectors.push(this.minimum.clone());
  16227. this.vectors.push(this.maximum.clone());
  16228. this.vectors.push(this.minimum.clone());
  16229. this.vectors[2].x = this.maximum.x;
  16230. this.vectors.push(this.minimum.clone());
  16231. this.vectors[3].y = this.maximum.y;
  16232. this.vectors.push(this.minimum.clone());
  16233. this.vectors[4].z = this.maximum.z;
  16234. this.vectors.push(this.maximum.clone());
  16235. this.vectors[5].z = this.minimum.z;
  16236. this.vectors.push(this.maximum.clone());
  16237. this.vectors[6].x = this.minimum.x;
  16238. this.vectors.push(this.maximum.clone());
  16239. this.vectors[7].y = this.minimum.y;
  16240. // OBB
  16241. this.center = this.maximum.add(this.minimum).scale(0.5);
  16242. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16243. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16244. // World
  16245. for (var index = 0; index < this.vectors.length; index++) {
  16246. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16247. }
  16248. this.minimumWorld = BABYLON.Vector3.Zero();
  16249. this.maximumWorld = BABYLON.Vector3.Zero();
  16250. this.centerWorld = BABYLON.Vector3.Zero();
  16251. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16252. this._update(BABYLON.Matrix.Identity());
  16253. }
  16254. // Methods
  16255. BoundingBox.prototype.getWorldMatrix = function () {
  16256. return this._worldMatrix;
  16257. };
  16258. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16259. this._worldMatrix.copyFrom(matrix);
  16260. return this;
  16261. };
  16262. BoundingBox.prototype._update = function (world) {
  16263. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16264. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16265. for (var index = 0; index < this.vectors.length; index++) {
  16266. var v = this.vectorsWorld[index];
  16267. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16268. if (v.x < this.minimumWorld.x)
  16269. this.minimumWorld.x = v.x;
  16270. if (v.y < this.minimumWorld.y)
  16271. this.minimumWorld.y = v.y;
  16272. if (v.z < this.minimumWorld.z)
  16273. this.minimumWorld.z = v.z;
  16274. if (v.x > this.maximumWorld.x)
  16275. this.maximumWorld.x = v.x;
  16276. if (v.y > this.maximumWorld.y)
  16277. this.maximumWorld.y = v.y;
  16278. if (v.z > this.maximumWorld.z)
  16279. this.maximumWorld.z = v.z;
  16280. }
  16281. // Extend
  16282. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16283. this.extendSizeWorld.scaleInPlace(0.5);
  16284. // OBB
  16285. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16286. this.centerWorld.scaleInPlace(0.5);
  16287. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16288. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16289. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16290. this._worldMatrix = world;
  16291. };
  16292. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16293. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16294. };
  16295. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16296. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16297. };
  16298. BoundingBox.prototype.intersectsPoint = function (point) {
  16299. var delta = -BABYLON.Epsilon;
  16300. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16301. return false;
  16302. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16303. return false;
  16304. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16305. return false;
  16306. return true;
  16307. };
  16308. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16309. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16310. };
  16311. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16312. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16313. return false;
  16314. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16315. return false;
  16316. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16317. return false;
  16318. return true;
  16319. };
  16320. // Statics
  16321. BoundingBox.Intersects = function (box0, box1) {
  16322. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16323. return false;
  16324. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16325. return false;
  16326. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16327. return false;
  16328. return true;
  16329. };
  16330. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16331. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16332. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16333. return (num <= (sphereRadius * sphereRadius));
  16334. };
  16335. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16336. for (var p = 0; p < 6; p++) {
  16337. for (var i = 0; i < 8; i++) {
  16338. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16339. return false;
  16340. }
  16341. }
  16342. }
  16343. return true;
  16344. };
  16345. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16346. for (var p = 0; p < 6; p++) {
  16347. var inCount = 8;
  16348. for (var i = 0; i < 8; i++) {
  16349. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16350. --inCount;
  16351. }
  16352. else {
  16353. break;
  16354. }
  16355. }
  16356. if (inCount === 0)
  16357. return false;
  16358. }
  16359. return true;
  16360. };
  16361. return BoundingBox;
  16362. }());
  16363. BABYLON.BoundingBox = BoundingBox;
  16364. })(BABYLON || (BABYLON = {}));
  16365. //# sourceMappingURL=babylon.boundingBox.js.map
  16366. "use strict";
  16367. var BABYLON;
  16368. (function (BABYLON) {
  16369. var computeBoxExtents = function (axis, box) {
  16370. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16371. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16372. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16373. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16374. var r = r0 + r1 + r2;
  16375. return {
  16376. min: p - r,
  16377. max: p + r
  16378. };
  16379. };
  16380. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16381. var axisOverlap = function (axis, box0, box1) {
  16382. var result0 = computeBoxExtents(axis, box0);
  16383. var result1 = computeBoxExtents(axis, box1);
  16384. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16385. };
  16386. var BoundingInfo = /** @class */ (function () {
  16387. function BoundingInfo(minimum, maximum) {
  16388. this.minimum = minimum;
  16389. this.maximum = maximum;
  16390. this._isLocked = false;
  16391. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16392. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16393. }
  16394. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16395. get: function () {
  16396. return this._isLocked;
  16397. },
  16398. set: function (value) {
  16399. this._isLocked = value;
  16400. },
  16401. enumerable: true,
  16402. configurable: true
  16403. });
  16404. // Methods
  16405. BoundingInfo.prototype.update = function (world) {
  16406. if (this._isLocked) {
  16407. return;
  16408. }
  16409. this.boundingBox._update(world);
  16410. this.boundingSphere._update(world);
  16411. };
  16412. /**
  16413. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16414. * @param center New center of the bounding info
  16415. * @param extend New extend of the bounding info
  16416. */
  16417. BoundingInfo.prototype.centerOn = function (center, extend) {
  16418. this.minimum = center.subtract(extend);
  16419. this.maximum = center.add(extend);
  16420. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16421. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16422. return this;
  16423. };
  16424. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16425. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16426. return false;
  16427. return this.boundingBox.isInFrustum(frustumPlanes);
  16428. };
  16429. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16430. /**
  16431. * Gets the world distance between the min and max points of the bounding box
  16432. */
  16433. get: function () {
  16434. var boundingBox = this.boundingBox;
  16435. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16436. return size.length();
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16442. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16443. };
  16444. BoundingInfo.prototype._checkCollision = function (collider) {
  16445. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16446. };
  16447. BoundingInfo.prototype.intersectsPoint = function (point) {
  16448. if (!this.boundingSphere.centerWorld) {
  16449. return false;
  16450. }
  16451. if (!this.boundingSphere.intersectsPoint(point)) {
  16452. return false;
  16453. }
  16454. if (!this.boundingBox.intersectsPoint(point)) {
  16455. return false;
  16456. }
  16457. return true;
  16458. };
  16459. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16460. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16461. return false;
  16462. }
  16463. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16464. return false;
  16465. }
  16466. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16467. return false;
  16468. }
  16469. if (!precise) {
  16470. return true;
  16471. }
  16472. var box0 = this.boundingBox;
  16473. var box1 = boundingInfo.boundingBox;
  16474. if (!axisOverlap(box0.directions[0], box0, box1))
  16475. return false;
  16476. if (!axisOverlap(box0.directions[1], box0, box1))
  16477. return false;
  16478. if (!axisOverlap(box0.directions[2], box0, box1))
  16479. return false;
  16480. if (!axisOverlap(box1.directions[0], box0, box1))
  16481. return false;
  16482. if (!axisOverlap(box1.directions[1], box0, box1))
  16483. return false;
  16484. if (!axisOverlap(box1.directions[2], box0, box1))
  16485. return false;
  16486. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16487. return false;
  16488. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16489. return false;
  16490. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16491. return false;
  16492. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16493. return false;
  16494. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16495. return false;
  16496. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16497. return false;
  16498. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16499. return false;
  16500. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16501. return false;
  16502. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16503. return false;
  16504. return true;
  16505. };
  16506. return BoundingInfo;
  16507. }());
  16508. BABYLON.BoundingInfo = BoundingInfo;
  16509. })(BABYLON || (BABYLON = {}));
  16510. //# sourceMappingURL=babylon.boundingInfo.js.map
  16511. "use strict";
  16512. var BABYLON;
  16513. (function (BABYLON) {
  16514. var TransformNode = /** @class */ (function (_super) {
  16515. __extends(TransformNode, _super);
  16516. function TransformNode(name, scene, isPure) {
  16517. if (scene === void 0) { scene = null; }
  16518. if (isPure === void 0) { isPure = true; }
  16519. var _this = _super.call(this, name, scene) || this;
  16520. _this._forward = new BABYLON.Vector3(0, 0, 1);
  16521. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  16522. _this._up = new BABYLON.Vector3(0, 1, 0);
  16523. _this._right = new BABYLON.Vector3(1, 0, 0);
  16524. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  16525. // Properties
  16526. _this._rotation = BABYLON.Vector3.Zero();
  16527. _this._scaling = BABYLON.Vector3.One();
  16528. _this._isDirty = false;
  16529. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  16530. _this.scalingDeterminant = 1;
  16531. _this.infiniteDistance = false;
  16532. _this.position = BABYLON.Vector3.Zero();
  16533. _this._localWorld = BABYLON.Matrix.Zero();
  16534. _this._worldMatrix = BABYLON.Matrix.Zero();
  16535. _this._worldMatrixDeterminant = 0;
  16536. _this._absolutePosition = BABYLON.Vector3.Zero();
  16537. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16538. _this._postMultiplyPivotMatrix = false;
  16539. _this._isWorldMatrixFrozen = false;
  16540. /**
  16541. * An event triggered after the world matrix is updated
  16542. * @type {BABYLON.Observable}
  16543. */
  16544. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16545. _this._nonUniformScaling = false;
  16546. if (isPure) {
  16547. _this.getScene().addTransformNode(_this);
  16548. }
  16549. return _this;
  16550. }
  16551. /**
  16552. * Gets a string idenfifying the name of the class
  16553. * @returns "TransformNode" string
  16554. */
  16555. TransformNode.prototype.getClassName = function () {
  16556. return "TransformNode";
  16557. };
  16558. Object.defineProperty(TransformNode.prototype, "rotation", {
  16559. /**
  16560. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16561. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16562. * Default : (0.0, 0.0, 0.0)
  16563. */
  16564. get: function () {
  16565. return this._rotation;
  16566. },
  16567. set: function (newRotation) {
  16568. this._rotation = newRotation;
  16569. },
  16570. enumerable: true,
  16571. configurable: true
  16572. });
  16573. Object.defineProperty(TransformNode.prototype, "scaling", {
  16574. /**
  16575. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16576. * Default : (1.0, 1.0, 1.0)
  16577. */
  16578. get: function () {
  16579. return this._scaling;
  16580. },
  16581. /**
  16582. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16583. * Default : (1.0, 1.0, 1.0)
  16584. */
  16585. set: function (newScaling) {
  16586. this._scaling = newScaling;
  16587. },
  16588. enumerable: true,
  16589. configurable: true
  16590. });
  16591. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16592. /**
  16593. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16594. * It's null by default.
  16595. * 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)
  16596. */
  16597. get: function () {
  16598. return this._rotationQuaternion;
  16599. },
  16600. set: function (quaternion) {
  16601. this._rotationQuaternion = quaternion;
  16602. //reset the rotation vector.
  16603. if (quaternion && this.rotation.length()) {
  16604. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16605. }
  16606. },
  16607. enumerable: true,
  16608. configurable: true
  16609. });
  16610. Object.defineProperty(TransformNode.prototype, "forward", {
  16611. /**
  16612. * The forward direction of that transform in world space.
  16613. */
  16614. get: function () {
  16615. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  16616. },
  16617. enumerable: true,
  16618. configurable: true
  16619. });
  16620. Object.defineProperty(TransformNode.prototype, "up", {
  16621. /**
  16622. * The up direction of that transform in world space.
  16623. */
  16624. get: function () {
  16625. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  16626. },
  16627. enumerable: true,
  16628. configurable: true
  16629. });
  16630. Object.defineProperty(TransformNode.prototype, "right", {
  16631. /**
  16632. * The right direction of that transform in world space.
  16633. */
  16634. get: function () {
  16635. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  16636. },
  16637. enumerable: true,
  16638. configurable: true
  16639. });
  16640. /**
  16641. * Returns the latest update of the World matrix
  16642. * Returns a Matrix.
  16643. */
  16644. TransformNode.prototype.getWorldMatrix = function () {
  16645. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16646. this.computeWorldMatrix();
  16647. }
  16648. return this._worldMatrix;
  16649. };
  16650. /**
  16651. * Returns the latest update of the World matrix determinant.
  16652. */
  16653. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16654. return this._worldMatrixDeterminant;
  16655. };
  16656. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16657. /**
  16658. * Returns directly the latest state of the mesh World matrix.
  16659. * A Matrix is returned.
  16660. */
  16661. get: function () {
  16662. return this._worldMatrix;
  16663. },
  16664. enumerable: true,
  16665. configurable: true
  16666. });
  16667. /**
  16668. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16669. * Returns the TransformNode.
  16670. */
  16671. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16672. this._poseMatrix.copyFrom(matrix);
  16673. return this;
  16674. };
  16675. /**
  16676. * Returns the mesh Pose matrix.
  16677. * Returned object : Matrix
  16678. */
  16679. TransformNode.prototype.getPoseMatrix = function () {
  16680. return this._poseMatrix;
  16681. };
  16682. TransformNode.prototype._isSynchronized = function () {
  16683. if (this._isDirty) {
  16684. return false;
  16685. }
  16686. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  16687. return false;
  16688. if (this._cache.pivotMatrixUpdated) {
  16689. return false;
  16690. }
  16691. if (this.infiniteDistance) {
  16692. return false;
  16693. }
  16694. if (!this._cache.position.equals(this.position))
  16695. return false;
  16696. if (this.rotationQuaternion) {
  16697. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16698. return false;
  16699. }
  16700. if (!this._cache.rotation.equals(this.rotation))
  16701. return false;
  16702. if (!this._cache.scaling.equals(this.scaling))
  16703. return false;
  16704. return true;
  16705. };
  16706. TransformNode.prototype._initCache = function () {
  16707. _super.prototype._initCache.call(this);
  16708. this._cache.localMatrixUpdated = false;
  16709. this._cache.position = BABYLON.Vector3.Zero();
  16710. this._cache.scaling = BABYLON.Vector3.Zero();
  16711. this._cache.rotation = BABYLON.Vector3.Zero();
  16712. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16713. this._cache.billboardMode = -1;
  16714. };
  16715. TransformNode.prototype.markAsDirty = function (property) {
  16716. if (property === "rotation") {
  16717. this.rotationQuaternion = null;
  16718. }
  16719. this._currentRenderId = Number.MAX_VALUE;
  16720. this._isDirty = true;
  16721. return this;
  16722. };
  16723. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16724. /**
  16725. * Returns the current mesh absolute position.
  16726. * Retuns a Vector3.
  16727. */
  16728. get: function () {
  16729. return this._absolutePosition;
  16730. },
  16731. enumerable: true,
  16732. configurable: true
  16733. });
  16734. /**
  16735. * Sets a new matrix to apply before all other transformation
  16736. * @param matrix defines the transform matrix
  16737. * @returns the current TransformNode
  16738. */
  16739. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16740. return this.setPivotMatrix(matrix, false);
  16741. };
  16742. /**
  16743. * Sets a new pivot matrix to the current node
  16744. * @param matrix defines the new pivot matrix to use
  16745. * @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
  16746. * @returns the current TransformNode
  16747. */
  16748. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16749. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16750. this._pivotMatrix = matrix.clone();
  16751. this._cache.pivotMatrixUpdated = true;
  16752. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16753. if (this._postMultiplyPivotMatrix) {
  16754. if (!this._pivotMatrixInverse) {
  16755. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16756. }
  16757. else {
  16758. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16759. }
  16760. }
  16761. return this;
  16762. };
  16763. /**
  16764. * Returns the mesh pivot matrix.
  16765. * Default : Identity.
  16766. * A Matrix is returned.
  16767. */
  16768. TransformNode.prototype.getPivotMatrix = function () {
  16769. return this._pivotMatrix;
  16770. };
  16771. /**
  16772. * Prevents the World matrix to be computed any longer.
  16773. * Returns the TransformNode.
  16774. */
  16775. TransformNode.prototype.freezeWorldMatrix = function () {
  16776. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16777. this.computeWorldMatrix(true);
  16778. this._isWorldMatrixFrozen = true;
  16779. return this;
  16780. };
  16781. /**
  16782. * Allows back the World matrix computation.
  16783. * Returns the TransformNode.
  16784. */
  16785. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16786. this._isWorldMatrixFrozen = false;
  16787. this.computeWorldMatrix(true);
  16788. return this;
  16789. };
  16790. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16791. /**
  16792. * True if the World matrix has been frozen.
  16793. * Returns a boolean.
  16794. */
  16795. get: function () {
  16796. return this._isWorldMatrixFrozen;
  16797. },
  16798. enumerable: true,
  16799. configurable: true
  16800. });
  16801. /**
  16802. * Retuns the mesh absolute position in the World.
  16803. * Returns a Vector3.
  16804. */
  16805. TransformNode.prototype.getAbsolutePosition = function () {
  16806. this.computeWorldMatrix();
  16807. return this._absolutePosition;
  16808. };
  16809. /**
  16810. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16811. * Returns the TransformNode.
  16812. */
  16813. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16814. if (!absolutePosition) {
  16815. return this;
  16816. }
  16817. var absolutePositionX;
  16818. var absolutePositionY;
  16819. var absolutePositionZ;
  16820. if (absolutePosition.x === undefined) {
  16821. if (arguments.length < 3) {
  16822. return this;
  16823. }
  16824. absolutePositionX = arguments[0];
  16825. absolutePositionY = arguments[1];
  16826. absolutePositionZ = arguments[2];
  16827. }
  16828. else {
  16829. absolutePositionX = absolutePosition.x;
  16830. absolutePositionY = absolutePosition.y;
  16831. absolutePositionZ = absolutePosition.z;
  16832. }
  16833. if (this.parent) {
  16834. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16835. invertParentWorldMatrix.invert();
  16836. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16837. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16838. }
  16839. else {
  16840. this.position.x = absolutePositionX;
  16841. this.position.y = absolutePositionY;
  16842. this.position.z = absolutePositionZ;
  16843. }
  16844. return this;
  16845. };
  16846. /**
  16847. * Sets the mesh position in its local space.
  16848. * Returns the TransformNode.
  16849. */
  16850. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16851. this.computeWorldMatrix();
  16852. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16853. return this;
  16854. };
  16855. /**
  16856. * Returns the mesh position in the local space from the current World matrix values.
  16857. * Returns a new Vector3.
  16858. */
  16859. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16860. this.computeWorldMatrix();
  16861. var invLocalWorldMatrix = this._localWorld.clone();
  16862. invLocalWorldMatrix.invert();
  16863. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16864. };
  16865. /**
  16866. * Translates the mesh along the passed Vector3 in its local space.
  16867. * Returns the TransformNode.
  16868. */
  16869. TransformNode.prototype.locallyTranslate = function (vector3) {
  16870. this.computeWorldMatrix(true);
  16871. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16872. return this;
  16873. };
  16874. /**
  16875. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16876. * @param targetPoint the position (must be in same space as current mesh) to look at
  16877. * @param yawCor optional yaw (y-axis) correction in radians
  16878. * @param pitchCor optional pitch (x-axis) correction in radians
  16879. * @param rollCor optional roll (z-axis) correction in radians
  16880. * @param space the choosen space of the target
  16881. * @returns the TransformNode.
  16882. */
  16883. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16884. if (yawCor === void 0) { yawCor = 0; }
  16885. if (pitchCor === void 0) { pitchCor = 0; }
  16886. if (rollCor === void 0) { rollCor = 0; }
  16887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16888. var dv = TransformNode._lookAtVectorCache;
  16889. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16890. targetPoint.subtractToRef(pos, dv);
  16891. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16892. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16893. var pitch = Math.atan2(dv.y, len);
  16894. if (this.rotationQuaternion) {
  16895. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16896. }
  16897. else {
  16898. this.rotation.x = pitch + pitchCor;
  16899. this.rotation.y = yaw + yawCor;
  16900. this.rotation.z = rollCor;
  16901. }
  16902. return this;
  16903. };
  16904. /**
  16905. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16906. * This Vector3 is expressed in the World space.
  16907. */
  16908. TransformNode.prototype.getDirection = function (localAxis) {
  16909. var result = BABYLON.Vector3.Zero();
  16910. this.getDirectionToRef(localAxis, result);
  16911. return result;
  16912. };
  16913. /**
  16914. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16915. * localAxis is expressed in the mesh local space.
  16916. * result is computed in the Wordl space from the mesh World matrix.
  16917. * Returns the TransformNode.
  16918. */
  16919. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16920. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16921. return this;
  16922. };
  16923. /**
  16924. * Sets a new pivot point to the current node
  16925. * @param point defines the new pivot point to use
  16926. * @param space defines if the point is in world or local space (local by default)
  16927. * @returns the current TransformNode
  16928. */
  16929. TransformNode.prototype.setPivotPoint = function (point, space) {
  16930. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16931. if (this.getScene().getRenderId() == 0) {
  16932. this.computeWorldMatrix(true);
  16933. }
  16934. var wm = this.getWorldMatrix();
  16935. if (space == BABYLON.Space.WORLD) {
  16936. var tmat = BABYLON.Tmp.Matrix[0];
  16937. wm.invertToRef(tmat);
  16938. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16939. }
  16940. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16941. };
  16942. /**
  16943. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16944. */
  16945. TransformNode.prototype.getPivotPoint = function () {
  16946. var point = BABYLON.Vector3.Zero();
  16947. this.getPivotPointToRef(point);
  16948. return point;
  16949. };
  16950. /**
  16951. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16952. * Returns the TransformNode.
  16953. */
  16954. TransformNode.prototype.getPivotPointToRef = function (result) {
  16955. result.x = -this._pivotMatrix.m[12];
  16956. result.y = -this._pivotMatrix.m[13];
  16957. result.z = -this._pivotMatrix.m[14];
  16958. return this;
  16959. };
  16960. /**
  16961. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16962. */
  16963. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16964. var point = BABYLON.Vector3.Zero();
  16965. this.getAbsolutePivotPointToRef(point);
  16966. return point;
  16967. };
  16968. /**
  16969. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16970. * Returns the TransformNode.
  16971. */
  16972. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16973. result.x = this._pivotMatrix.m[12];
  16974. result.y = this._pivotMatrix.m[13];
  16975. result.z = this._pivotMatrix.m[14];
  16976. this.getPivotPointToRef(result);
  16977. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16978. return this;
  16979. };
  16980. /**
  16981. * Defines the passed node as the parent of the current node.
  16982. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16983. * Returns the TransformNode.
  16984. */
  16985. TransformNode.prototype.setParent = function (node) {
  16986. if (node === null) {
  16987. var rotation = BABYLON.Tmp.Quaternion[0];
  16988. var position = BABYLON.Tmp.Vector3[0];
  16989. var scale = BABYLON.Tmp.Vector3[1];
  16990. if (this.parent && this.parent.computeWorldMatrix) {
  16991. this.parent.computeWorldMatrix(true);
  16992. }
  16993. this.computeWorldMatrix(true);
  16994. this.getWorldMatrix().decompose(scale, rotation, position);
  16995. if (this.rotationQuaternion) {
  16996. this.rotationQuaternion.copyFrom(rotation);
  16997. }
  16998. else {
  16999. rotation.toEulerAnglesToRef(this.rotation);
  17000. }
  17001. this.scaling.x = scale.x;
  17002. this.scaling.y = scale.y;
  17003. this.scaling.z = scale.z;
  17004. this.position.x = position.x;
  17005. this.position.y = position.y;
  17006. this.position.z = position.z;
  17007. }
  17008. else {
  17009. var rotation = BABYLON.Tmp.Quaternion[0];
  17010. var position = BABYLON.Tmp.Vector3[0];
  17011. var scale = BABYLON.Tmp.Vector3[1];
  17012. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17013. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17014. this.computeWorldMatrix(true);
  17015. node.computeWorldMatrix(true);
  17016. node.getWorldMatrix().invertToRef(invParentMatrix);
  17017. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17018. diffMatrix.decompose(scale, rotation, position);
  17019. if (this.rotationQuaternion) {
  17020. this.rotationQuaternion.copyFrom(rotation);
  17021. }
  17022. else {
  17023. rotation.toEulerAnglesToRef(this.rotation);
  17024. }
  17025. this.position.x = position.x;
  17026. this.position.y = position.y;
  17027. this.position.z = position.z;
  17028. this.scaling.x = scale.x;
  17029. this.scaling.y = scale.y;
  17030. this.scaling.z = scale.z;
  17031. }
  17032. this.parent = node;
  17033. return this;
  17034. };
  17035. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17036. get: function () {
  17037. return this._nonUniformScaling;
  17038. },
  17039. enumerable: true,
  17040. configurable: true
  17041. });
  17042. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17043. if (this._nonUniformScaling === value) {
  17044. return false;
  17045. }
  17046. this._nonUniformScaling = true;
  17047. return true;
  17048. };
  17049. /**
  17050. * Attach the current TransformNode to another TransformNode associated with a bone
  17051. * @param bone Bone affecting the TransformNode
  17052. * @param affectedTransformNode TransformNode associated with the bone
  17053. */
  17054. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17055. this._transformToBoneReferal = affectedTransformNode;
  17056. this.parent = bone;
  17057. if (bone.getWorldMatrix().determinant() < 0) {
  17058. this.scalingDeterminant *= -1;
  17059. }
  17060. return this;
  17061. };
  17062. TransformNode.prototype.detachFromBone = function () {
  17063. if (!this.parent) {
  17064. return this;
  17065. }
  17066. if (this.parent.getWorldMatrix().determinant() < 0) {
  17067. this.scalingDeterminant *= -1;
  17068. }
  17069. this._transformToBoneReferal = null;
  17070. this.parent = null;
  17071. return this;
  17072. };
  17073. /**
  17074. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17075. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17076. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17077. * The passed axis is also normalized.
  17078. * Returns the TransformNode.
  17079. */
  17080. TransformNode.prototype.rotate = function (axis, amount, space) {
  17081. axis.normalize();
  17082. if (!this.rotationQuaternion) {
  17083. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17084. this.rotation = BABYLON.Vector3.Zero();
  17085. }
  17086. var rotationQuaternion;
  17087. if (!space || space === BABYLON.Space.LOCAL) {
  17088. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17089. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17090. }
  17091. else {
  17092. if (this.parent) {
  17093. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17094. invertParentWorldMatrix.invert();
  17095. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17096. }
  17097. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  17098. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17099. }
  17100. return this;
  17101. };
  17102. /**
  17103. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17104. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17105. * The passed axis is also normalized.
  17106. * Returns the TransformNode.
  17107. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17108. */
  17109. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17110. axis.normalize();
  17111. if (!this.rotationQuaternion) {
  17112. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17113. this.rotation.copyFromFloats(0, 0, 0);
  17114. }
  17115. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17116. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17117. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17118. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17119. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17120. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17121. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17122. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17123. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17124. return this;
  17125. };
  17126. /**
  17127. * Translates the mesh along the axis vector for the passed distance in the given space.
  17128. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17129. * Returns the TransformNode.
  17130. */
  17131. TransformNode.prototype.translate = function (axis, distance, space) {
  17132. var displacementVector = axis.scale(distance);
  17133. if (!space || space === BABYLON.Space.LOCAL) {
  17134. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17135. this.setPositionWithLocalVector(tempV3);
  17136. }
  17137. else {
  17138. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17139. }
  17140. return this;
  17141. };
  17142. /**
  17143. * Adds a rotation step to the mesh current rotation.
  17144. * x, y, z are Euler angles expressed in radians.
  17145. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17146. * This means this rotation is made in the mesh local space only.
  17147. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17148. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17149. * ```javascript
  17150. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17151. * ```
  17152. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17153. * 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.
  17154. * Returns the TransformNode.
  17155. */
  17156. TransformNode.prototype.addRotation = function (x, y, z) {
  17157. var rotationQuaternion;
  17158. if (this.rotationQuaternion) {
  17159. rotationQuaternion = this.rotationQuaternion;
  17160. }
  17161. else {
  17162. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17163. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17164. }
  17165. var accumulation = BABYLON.Tmp.Quaternion[0];
  17166. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17167. rotationQuaternion.multiplyInPlace(accumulation);
  17168. if (!this.rotationQuaternion) {
  17169. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17170. }
  17171. return this;
  17172. };
  17173. /**
  17174. * Computes the mesh World matrix and returns it.
  17175. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17176. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17177. * If the parameter `force`is set to `true`, the actual computation is done.
  17178. * Returns the mesh World Matrix.
  17179. */
  17180. TransformNode.prototype.computeWorldMatrix = function (force) {
  17181. if (this._isWorldMatrixFrozen) {
  17182. return this._worldMatrix;
  17183. }
  17184. if (!force && this.isSynchronized(true)) {
  17185. this._currentRenderId = this.getScene().getRenderId();
  17186. return this._worldMatrix;
  17187. }
  17188. this._cache.position.copyFrom(this.position);
  17189. this._cache.scaling.copyFrom(this.scaling);
  17190. this._cache.pivotMatrixUpdated = false;
  17191. this._cache.billboardMode = this.billboardMode;
  17192. this._currentRenderId = this.getScene().getRenderId();
  17193. this._childRenderId = this.getScene().getRenderId();
  17194. this._isDirty = false;
  17195. // Scaling
  17196. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17197. // Rotation
  17198. //rotate, if quaternion is set and rotation was used
  17199. if (this.rotationQuaternion) {
  17200. var len = this.rotation.length();
  17201. if (len) {
  17202. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17203. this.rotation.copyFromFloats(0, 0, 0);
  17204. }
  17205. }
  17206. if (this.rotationQuaternion) {
  17207. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17208. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17209. }
  17210. else {
  17211. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17212. this._cache.rotation.copyFrom(this.rotation);
  17213. }
  17214. // Translation
  17215. var camera = this.getScene().activeCamera;
  17216. if (this.infiniteDistance && !this.parent && camera) {
  17217. var cameraWorldMatrix = camera.getWorldMatrix();
  17218. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17219. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17220. }
  17221. else {
  17222. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17223. }
  17224. // Composing transformations
  17225. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17226. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17227. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17228. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  17229. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  17230. // Need to decompose each rotation here
  17231. var currentPosition = BABYLON.Tmp.Vector3[3];
  17232. if (this.parent && this.parent.getWorldMatrix) {
  17233. if (this._transformToBoneReferal) {
  17234. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17235. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17236. }
  17237. else {
  17238. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17239. }
  17240. }
  17241. else {
  17242. currentPosition.copyFrom(this.position);
  17243. }
  17244. currentPosition.subtractInPlace(camera.globalPosition);
  17245. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17246. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  17247. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17248. }
  17249. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  17250. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17251. }
  17252. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  17253. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17254. }
  17255. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17256. }
  17257. else {
  17258. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17259. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17260. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17261. }
  17262. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17263. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17264. }
  17265. // Local world
  17266. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17267. // Parent
  17268. if (this.parent && this.parent.getWorldMatrix) {
  17269. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  17270. if (this._transformToBoneReferal) {
  17271. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17272. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17273. }
  17274. else {
  17275. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17276. }
  17277. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17278. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17279. this._worldMatrix.copyFrom(this._localWorld);
  17280. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17281. }
  17282. else {
  17283. if (this._transformToBoneReferal) {
  17284. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17285. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17286. }
  17287. else {
  17288. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17289. }
  17290. }
  17291. this._markSyncedWithParent();
  17292. }
  17293. else {
  17294. this._worldMatrix.copyFrom(this._localWorld);
  17295. }
  17296. // Post multiply inverse of pivotMatrix
  17297. if (this._postMultiplyPivotMatrix) {
  17298. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17299. }
  17300. // Normal matrix
  17301. if (this.scaling.isNonUniform) {
  17302. this._updateNonUniformScalingState(true);
  17303. }
  17304. else if (this.parent && this.parent._nonUniformScaling) {
  17305. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17306. }
  17307. else {
  17308. this._updateNonUniformScalingState(false);
  17309. }
  17310. this._afterComputeWorldMatrix();
  17311. // Absolute position
  17312. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17313. // Callbacks
  17314. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17315. if (!this._poseMatrix) {
  17316. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17317. }
  17318. // Cache the determinant
  17319. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17320. return this._worldMatrix;
  17321. };
  17322. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17323. };
  17324. /**
  17325. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17326. * @param func: callback function to add
  17327. *
  17328. * Returns the TransformNode.
  17329. */
  17330. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17331. this.onAfterWorldMatrixUpdateObservable.add(func);
  17332. return this;
  17333. };
  17334. /**
  17335. * Removes a registered callback function.
  17336. * Returns the TransformNode.
  17337. */
  17338. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17339. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17340. return this;
  17341. };
  17342. /**
  17343. * Clone the current transform node
  17344. * Returns the new transform node
  17345. * @param name Name of the new clone
  17346. * @param newParent New parent for the clone
  17347. * @param doNotCloneChildren Do not clone children hierarchy
  17348. */
  17349. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17350. var _this = this;
  17351. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17352. result.name = name;
  17353. result.id = name;
  17354. if (newParent) {
  17355. result.parent = newParent;
  17356. }
  17357. if (!doNotCloneChildren) {
  17358. // Children
  17359. var directDescendants = this.getDescendants(true);
  17360. for (var index = 0; index < directDescendants.length; index++) {
  17361. var child = directDescendants[index];
  17362. if (child.clone) {
  17363. child.clone(name + "." + child.name, result);
  17364. }
  17365. }
  17366. }
  17367. return result;
  17368. };
  17369. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17370. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17371. serializationObject.type = this.getClassName();
  17372. // Parent
  17373. if (this.parent) {
  17374. serializationObject.parentId = this.parent.id;
  17375. }
  17376. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17377. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17378. }
  17379. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17380. serializationObject.isEnabled = this.isEnabled();
  17381. // Parent
  17382. if (this.parent) {
  17383. serializationObject.parentId = this.parent.id;
  17384. }
  17385. return serializationObject;
  17386. };
  17387. // Statics
  17388. /**
  17389. * Returns a new TransformNode object parsed from the source provided.
  17390. * The parameter `parsedMesh` is the source.
  17391. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17392. */
  17393. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17394. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17395. if (BABYLON.Tags) {
  17396. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17397. }
  17398. if (parsedTransformNode.localMatrix) {
  17399. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17400. }
  17401. else if (parsedTransformNode.pivotMatrix) {
  17402. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17403. }
  17404. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17405. // Parent
  17406. if (parsedTransformNode.parentId) {
  17407. transformNode._waitingParentId = parsedTransformNode.parentId;
  17408. }
  17409. return transformNode;
  17410. };
  17411. /**
  17412. * Releases resources associated with this transform node.
  17413. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17414. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17415. */
  17416. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17417. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17418. // Animations
  17419. this.getScene().stopAnimation(this);
  17420. // Remove from scene
  17421. this.getScene().removeTransformNode(this);
  17422. this.onAfterWorldMatrixUpdateObservable.clear();
  17423. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17424. };
  17425. // Statics
  17426. TransformNode.BILLBOARDMODE_NONE = 0;
  17427. TransformNode.BILLBOARDMODE_X = 1;
  17428. TransformNode.BILLBOARDMODE_Y = 2;
  17429. TransformNode.BILLBOARDMODE_Z = 4;
  17430. TransformNode.BILLBOARDMODE_ALL = 7;
  17431. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17432. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17433. __decorate([
  17434. BABYLON.serializeAsVector3()
  17435. ], TransformNode.prototype, "_rotation", void 0);
  17436. __decorate([
  17437. BABYLON.serializeAsQuaternion()
  17438. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17439. __decorate([
  17440. BABYLON.serializeAsVector3()
  17441. ], TransformNode.prototype, "_scaling", void 0);
  17442. __decorate([
  17443. BABYLON.serialize()
  17444. ], TransformNode.prototype, "billboardMode", void 0);
  17445. __decorate([
  17446. BABYLON.serialize()
  17447. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17448. __decorate([
  17449. BABYLON.serialize()
  17450. ], TransformNode.prototype, "infiniteDistance", void 0);
  17451. __decorate([
  17452. BABYLON.serializeAsVector3()
  17453. ], TransformNode.prototype, "position", void 0);
  17454. return TransformNode;
  17455. }(BABYLON.Node));
  17456. BABYLON.TransformNode = TransformNode;
  17457. })(BABYLON || (BABYLON = {}));
  17458. //# sourceMappingURL=babylon.transformNode.js.map
  17459. "use strict";
  17460. var BABYLON;
  17461. (function (BABYLON) {
  17462. var AbstractMesh = /** @class */ (function (_super) {
  17463. __extends(AbstractMesh, _super);
  17464. // Constructor
  17465. function AbstractMesh(name, scene) {
  17466. if (scene === void 0) { scene = null; }
  17467. var _this = _super.call(this, name, scene, false) || this;
  17468. _this._facetNb = 0; // facet number
  17469. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17470. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17471. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17472. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17473. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17474. _this._subDiv = {
  17475. max: 1,
  17476. X: 1,
  17477. Y: 1,
  17478. Z: 1
  17479. };
  17480. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17481. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17482. // Events
  17483. /**
  17484. * An event triggered when this mesh collides with another one
  17485. * @type {BABYLON.Observable}
  17486. */
  17487. _this.onCollideObservable = new BABYLON.Observable();
  17488. /**
  17489. * An event triggered when the collision's position changes
  17490. * @type {BABYLON.Observable}
  17491. */
  17492. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17493. /**
  17494. * An event triggered when material is changed
  17495. * @type {BABYLON.Observable}
  17496. */
  17497. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17498. // Properties
  17499. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17500. /**
  17501. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17502. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17503. * or
  17504. * 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.
  17505. * for more info check WebGl documentations
  17506. */
  17507. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17508. /**
  17509. * 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:
  17510. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17511. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17512. * 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.
  17513. */
  17514. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17515. /**
  17516. * 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.
  17517. * The default value is -1 which means don't break the query and wait till the result.
  17518. */
  17519. _this.occlusionRetryCount = -1;
  17520. _this._occlusionInternalRetryCounter = 0;
  17521. _this._isOccluded = false;
  17522. _this._isOcclusionQueryInProgress = false;
  17523. _this._visibility = 1.0;
  17524. _this.alphaIndex = Number.MAX_VALUE;
  17525. _this.isVisible = true;
  17526. _this.isPickable = true;
  17527. _this.showBoundingBox = false;
  17528. _this.showSubMeshesBoundingBox = false;
  17529. _this.isBlocker = false;
  17530. _this.enablePointerMoveEvents = false;
  17531. _this.renderingGroupId = 0;
  17532. _this._receiveShadows = false;
  17533. _this.renderOutline = false;
  17534. _this.outlineColor = BABYLON.Color3.Red();
  17535. _this.outlineWidth = 0.02;
  17536. _this.renderOverlay = false;
  17537. _this.overlayColor = BABYLON.Color3.Red();
  17538. _this.overlayAlpha = 0.5;
  17539. _this._hasVertexAlpha = false;
  17540. _this._useVertexColors = true;
  17541. _this._computeBonesUsingShaders = true;
  17542. _this._numBoneInfluencers = 4;
  17543. _this._applyFog = true;
  17544. _this.useOctreeForRenderingSelection = true;
  17545. _this.useOctreeForPicking = true;
  17546. _this.useOctreeForCollisions = true;
  17547. _this._layerMask = 0x0FFFFFFF;
  17548. /**
  17549. * True if the mesh must be rendered in any case.
  17550. */
  17551. _this.alwaysSelectAsActiveMesh = false;
  17552. /**
  17553. * This scene's action manager
  17554. * @type {BABYLON.ActionManager}
  17555. */
  17556. _this.actionManager = null;
  17557. // Physics
  17558. _this.physicsImpostor = null;
  17559. // Collisions
  17560. _this._checkCollisions = false;
  17561. _this._collisionMask = -1;
  17562. _this._collisionGroup = -1;
  17563. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17564. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17565. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17566. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17567. // Edges
  17568. _this.edgesWidth = 1;
  17569. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17570. // Cache
  17571. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17572. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17573. _this._renderId = 0;
  17574. _this._intersectionsInProgress = new Array();
  17575. _this._unIndexed = false;
  17576. _this._lightSources = new Array();
  17577. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17578. if (collidedMesh === void 0) { collidedMesh = null; }
  17579. //TODO move this to the collision coordinator!
  17580. if (_this.getScene().workerCollisions)
  17581. newPosition.multiplyInPlace(_this._collider._radius);
  17582. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17583. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17584. _this.position.addInPlace(_this._diffPositionForCollisions);
  17585. }
  17586. if (collidedMesh) {
  17587. _this.onCollideObservable.notifyObservers(collidedMesh);
  17588. }
  17589. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17590. };
  17591. _this.getScene().addMesh(_this);
  17592. _this._resyncLightSources();
  17593. return _this;
  17594. }
  17595. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17596. get: function () {
  17597. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17603. get: function () {
  17604. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17610. get: function () {
  17611. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17612. },
  17613. enumerable: true,
  17614. configurable: true
  17615. });
  17616. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17617. get: function () {
  17618. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17619. },
  17620. enumerable: true,
  17621. configurable: true
  17622. });
  17623. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17624. get: function () {
  17625. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17626. },
  17627. enumerable: true,
  17628. configurable: true
  17629. });
  17630. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17631. /**
  17632. * Read-only : the number of facets in the mesh
  17633. */
  17634. get: function () {
  17635. return this._facetNb;
  17636. },
  17637. enumerable: true,
  17638. configurable: true
  17639. });
  17640. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17641. /**
  17642. * The number (integer) of subdivisions per axis in the partioning space
  17643. */
  17644. get: function () {
  17645. return this._partitioningSubdivisions;
  17646. },
  17647. set: function (nb) {
  17648. this._partitioningSubdivisions = nb;
  17649. },
  17650. enumerable: true,
  17651. configurable: true
  17652. });
  17653. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17654. /**
  17655. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17656. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17657. */
  17658. get: function () {
  17659. return this._partitioningBBoxRatio;
  17660. },
  17661. set: function (ratio) {
  17662. this._partitioningBBoxRatio = ratio;
  17663. },
  17664. enumerable: true,
  17665. configurable: true
  17666. });
  17667. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17668. /**
  17669. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17670. * Works only for updatable meshes.
  17671. * Doesn't work with multi-materials.
  17672. */
  17673. get: function () {
  17674. return this._facetDepthSort;
  17675. },
  17676. set: function (sort) {
  17677. this._facetDepthSort = sort;
  17678. },
  17679. enumerable: true,
  17680. configurable: true
  17681. });
  17682. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17683. /**
  17684. * The location (Vector3) where the facet depth sort must be computed from.
  17685. * By default, the active camera position.
  17686. * Used only when facet depth sort is enabled.
  17687. */
  17688. get: function () {
  17689. return this._facetDepthSortFrom;
  17690. },
  17691. set: function (location) {
  17692. this._facetDepthSortFrom = location;
  17693. },
  17694. enumerable: true,
  17695. configurable: true
  17696. });
  17697. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17698. /**
  17699. * Read-only boolean : is the feature facetData enabled ?
  17700. */
  17701. get: function () {
  17702. return this._facetDataEnabled;
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17708. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17709. return false;
  17710. }
  17711. this._markSubMeshesAsMiscDirty();
  17712. return true;
  17713. };
  17714. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17715. set: function (callback) {
  17716. if (this._onCollideObserver) {
  17717. this.onCollideObservable.remove(this._onCollideObserver);
  17718. }
  17719. this._onCollideObserver = this.onCollideObservable.add(callback);
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17725. set: function (callback) {
  17726. if (this._onCollisionPositionChangeObserver) {
  17727. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17728. }
  17729. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17730. },
  17731. enumerable: true,
  17732. configurable: true
  17733. });
  17734. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17735. /**
  17736. * Property isOccluded : 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.
  17737. */
  17738. get: function () {
  17739. return this._isOccluded;
  17740. },
  17741. set: function (value) {
  17742. this._isOccluded = value;
  17743. },
  17744. enumerable: true,
  17745. configurable: true
  17746. });
  17747. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17748. /**
  17749. * Flag to check the progress status of the query
  17750. */
  17751. get: function () {
  17752. return this._isOcclusionQueryInProgress;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17758. /**
  17759. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17760. */
  17761. get: function () {
  17762. return this._visibility;
  17763. },
  17764. /**
  17765. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17766. */
  17767. set: function (value) {
  17768. if (this._visibility === value) {
  17769. return;
  17770. }
  17771. this._visibility = value;
  17772. this._markSubMeshesAsMiscDirty();
  17773. },
  17774. enumerable: true,
  17775. configurable: true
  17776. });
  17777. Object.defineProperty(AbstractMesh.prototype, "material", {
  17778. get: function () {
  17779. return this._material;
  17780. },
  17781. set: function (value) {
  17782. if (this._material === value) {
  17783. return;
  17784. }
  17785. this._material = value;
  17786. if (this.onMaterialChangedObservable.hasObservers) {
  17787. this.onMaterialChangedObservable.notifyObservers(this);
  17788. }
  17789. if (!this.subMeshes) {
  17790. return;
  17791. }
  17792. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17793. var subMesh = _a[_i];
  17794. subMesh.setEffect(null);
  17795. }
  17796. },
  17797. enumerable: true,
  17798. configurable: true
  17799. });
  17800. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17801. get: function () {
  17802. return this._receiveShadows;
  17803. },
  17804. set: function (value) {
  17805. if (this._receiveShadows === value) {
  17806. return;
  17807. }
  17808. this._receiveShadows = value;
  17809. this._markSubMeshesAsLightDirty();
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17815. get: function () {
  17816. return this._hasVertexAlpha;
  17817. },
  17818. set: function (value) {
  17819. if (this._hasVertexAlpha === value) {
  17820. return;
  17821. }
  17822. this._hasVertexAlpha = value;
  17823. this._markSubMeshesAsAttributesDirty();
  17824. this._markSubMeshesAsMiscDirty();
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17830. get: function () {
  17831. return this._useVertexColors;
  17832. },
  17833. set: function (value) {
  17834. if (this._useVertexColors === value) {
  17835. return;
  17836. }
  17837. this._useVertexColors = value;
  17838. this._markSubMeshesAsAttributesDirty();
  17839. },
  17840. enumerable: true,
  17841. configurable: true
  17842. });
  17843. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17844. get: function () {
  17845. return this._computeBonesUsingShaders;
  17846. },
  17847. set: function (value) {
  17848. if (this._computeBonesUsingShaders === value) {
  17849. return;
  17850. }
  17851. this._computeBonesUsingShaders = value;
  17852. this._markSubMeshesAsAttributesDirty();
  17853. },
  17854. enumerable: true,
  17855. configurable: true
  17856. });
  17857. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17858. get: function () {
  17859. return this._numBoneInfluencers;
  17860. },
  17861. set: function (value) {
  17862. if (this._numBoneInfluencers === value) {
  17863. return;
  17864. }
  17865. this._numBoneInfluencers = value;
  17866. this._markSubMeshesAsAttributesDirty();
  17867. },
  17868. enumerable: true,
  17869. configurable: true
  17870. });
  17871. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17872. get: function () {
  17873. return this._applyFog;
  17874. },
  17875. set: function (value) {
  17876. if (this._applyFog === value) {
  17877. return;
  17878. }
  17879. this._applyFog = value;
  17880. this._markSubMeshesAsMiscDirty();
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17886. get: function () {
  17887. return this._layerMask;
  17888. },
  17889. set: function (value) {
  17890. if (value === this._layerMask) {
  17891. return;
  17892. }
  17893. this._layerMask = value;
  17894. this._resyncLightSources();
  17895. },
  17896. enumerable: true,
  17897. configurable: true
  17898. });
  17899. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17900. get: function () {
  17901. return this._collisionMask;
  17902. },
  17903. set: function (mask) {
  17904. this._collisionMask = !isNaN(mask) ? mask : -1;
  17905. },
  17906. enumerable: true,
  17907. configurable: true
  17908. });
  17909. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17910. get: function () {
  17911. return this._collisionGroup;
  17912. },
  17913. set: function (mask) {
  17914. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17915. },
  17916. enumerable: true,
  17917. configurable: true
  17918. });
  17919. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17920. get: function () {
  17921. return null;
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17927. get: function () {
  17928. return this._skeleton;
  17929. },
  17930. set: function (value) {
  17931. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17932. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17933. }
  17934. if (value && value.needInitialSkinMatrix) {
  17935. value._registerMeshWithPoseMatrix(this);
  17936. }
  17937. this._skeleton = value;
  17938. if (!this._skeleton) {
  17939. this._bonesTransformMatrices = null;
  17940. }
  17941. this._markSubMeshesAsAttributesDirty();
  17942. },
  17943. enumerable: true,
  17944. configurable: true
  17945. });
  17946. /**
  17947. * Returns the string "AbstractMesh"
  17948. */
  17949. AbstractMesh.prototype.getClassName = function () {
  17950. return "AbstractMesh";
  17951. };
  17952. /**
  17953. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17954. */
  17955. AbstractMesh.prototype.toString = function (fullDetails) {
  17956. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17957. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17958. if (this._skeleton) {
  17959. ret += ", skeleton: " + this._skeleton.name;
  17960. }
  17961. if (fullDetails) {
  17962. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17963. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17964. }
  17965. return ret;
  17966. };
  17967. AbstractMesh.prototype._rebuild = function () {
  17968. if (this._occlusionQuery) {
  17969. this._occlusionQuery = null;
  17970. }
  17971. if (this._edgesRenderer) {
  17972. this._edgesRenderer._rebuild();
  17973. }
  17974. if (!this.subMeshes) {
  17975. return;
  17976. }
  17977. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17978. var subMesh = _a[_i];
  17979. subMesh._rebuild();
  17980. }
  17981. };
  17982. AbstractMesh.prototype._resyncLightSources = function () {
  17983. this._lightSources.length = 0;
  17984. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17985. var light = _a[_i];
  17986. if (!light.isEnabled()) {
  17987. continue;
  17988. }
  17989. if (light.canAffectMesh(this)) {
  17990. this._lightSources.push(light);
  17991. }
  17992. }
  17993. this._markSubMeshesAsLightDirty();
  17994. };
  17995. AbstractMesh.prototype._resyncLighSource = function (light) {
  17996. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17997. var index = this._lightSources.indexOf(light);
  17998. if (index === -1) {
  17999. if (!isIn) {
  18000. return;
  18001. }
  18002. this._lightSources.push(light);
  18003. }
  18004. else {
  18005. if (isIn) {
  18006. return;
  18007. }
  18008. this._lightSources.splice(index, 1);
  18009. }
  18010. this._markSubMeshesAsLightDirty();
  18011. };
  18012. AbstractMesh.prototype._removeLightSource = function (light) {
  18013. var index = this._lightSources.indexOf(light);
  18014. if (index === -1) {
  18015. return;
  18016. }
  18017. this._lightSources.splice(index, 1);
  18018. this._markSubMeshesAsLightDirty();
  18019. };
  18020. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18021. if (!this.subMeshes) {
  18022. return;
  18023. }
  18024. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18025. var subMesh = _a[_i];
  18026. if (subMesh._materialDefines) {
  18027. func(subMesh._materialDefines);
  18028. }
  18029. }
  18030. };
  18031. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18032. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18033. };
  18034. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18035. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18036. };
  18037. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18038. if (!this.subMeshes) {
  18039. return;
  18040. }
  18041. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18042. var subMesh = _a[_i];
  18043. var material = subMesh.getMaterial();
  18044. if (material) {
  18045. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18046. }
  18047. }
  18048. };
  18049. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18050. /**
  18051. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18052. * Default : (1.0, 1.0, 1.0)
  18053. */
  18054. get: function () {
  18055. return this._scaling;
  18056. },
  18057. /**
  18058. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18059. * Default : (1.0, 1.0, 1.0)
  18060. */
  18061. set: function (newScaling) {
  18062. this._scaling = newScaling;
  18063. if (this.physicsImpostor) {
  18064. this.physicsImpostor.forceUpdate();
  18065. }
  18066. },
  18067. enumerable: true,
  18068. configurable: true
  18069. });
  18070. // Methods
  18071. /**
  18072. * Disables the mesh edger rendering mode.
  18073. * Returns the AbstractMesh.
  18074. */
  18075. AbstractMesh.prototype.disableEdgesRendering = function () {
  18076. if (this._edgesRenderer) {
  18077. this._edgesRenderer.dispose();
  18078. this._edgesRenderer = null;
  18079. }
  18080. return this;
  18081. };
  18082. /**
  18083. * Enables the edge rendering mode on the mesh.
  18084. * This mode makes the mesh edges visible.
  18085. * Returns the AbstractMesh.
  18086. */
  18087. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18088. if (epsilon === void 0) { epsilon = 0.95; }
  18089. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18090. this.disableEdgesRendering();
  18091. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18092. return this;
  18093. };
  18094. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18095. /**
  18096. * Returns true if the mesh is blocked. Used by the class Mesh.
  18097. * Returns the boolean `false` by default.
  18098. */
  18099. get: function () {
  18100. return false;
  18101. },
  18102. enumerable: true,
  18103. configurable: true
  18104. });
  18105. /**
  18106. * Returns the mesh itself by default, used by the class Mesh.
  18107. * Returned type : AbstractMesh
  18108. */
  18109. AbstractMesh.prototype.getLOD = function (camera) {
  18110. return this;
  18111. };
  18112. /**
  18113. * Returns 0 by default, used by the class Mesh.
  18114. * Returns an integer.
  18115. */
  18116. AbstractMesh.prototype.getTotalVertices = function () {
  18117. return 0;
  18118. };
  18119. /**
  18120. * Returns null by default, used by the class Mesh.
  18121. * Returned type : integer array
  18122. */
  18123. AbstractMesh.prototype.getIndices = function () {
  18124. return null;
  18125. };
  18126. /**
  18127. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18128. * Returned type : float array or Float32Array
  18129. */
  18130. AbstractMesh.prototype.getVerticesData = function (kind) {
  18131. return null;
  18132. };
  18133. /**
  18134. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18135. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18136. * The `data` are either a numeric array either a Float32Array.
  18137. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18138. * 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).
  18139. * Note that a new underlying VertexBuffer object is created each call.
  18140. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18141. *
  18142. * Possible `kind` values :
  18143. * - BABYLON.VertexBuffer.PositionKind
  18144. * - BABYLON.VertexBuffer.UVKind
  18145. * - BABYLON.VertexBuffer.UV2Kind
  18146. * - BABYLON.VertexBuffer.UV3Kind
  18147. * - BABYLON.VertexBuffer.UV4Kind
  18148. * - BABYLON.VertexBuffer.UV5Kind
  18149. * - BABYLON.VertexBuffer.UV6Kind
  18150. * - BABYLON.VertexBuffer.ColorKind
  18151. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18152. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18153. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18154. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18155. *
  18156. * Returns the Mesh.
  18157. */
  18158. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18159. return this;
  18160. };
  18161. /**
  18162. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18163. * If the mesh has no geometry, it is simply returned as it is.
  18164. * The `data` are either a numeric array either a Float32Array.
  18165. * No new underlying VertexBuffer object is created.
  18166. * 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.
  18167. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18168. *
  18169. * Possible `kind` values :
  18170. * - BABYLON.VertexBuffer.PositionKind
  18171. * - BABYLON.VertexBuffer.UVKind
  18172. * - BABYLON.VertexBuffer.UV2Kind
  18173. * - BABYLON.VertexBuffer.UV3Kind
  18174. * - BABYLON.VertexBuffer.UV4Kind
  18175. * - BABYLON.VertexBuffer.UV5Kind
  18176. * - BABYLON.VertexBuffer.UV6Kind
  18177. * - BABYLON.VertexBuffer.ColorKind
  18178. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18179. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18180. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18181. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18182. *
  18183. * Returns the Mesh.
  18184. */
  18185. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18186. return this;
  18187. };
  18188. /**
  18189. * Sets the mesh indices.
  18190. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18191. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18192. * This method creates a new index buffer each call.
  18193. * Returns the Mesh.
  18194. */
  18195. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18196. return this;
  18197. };
  18198. /** Returns false by default, used by the class Mesh.
  18199. * Returns a boolean
  18200. */
  18201. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18202. return false;
  18203. };
  18204. /**
  18205. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18206. * Returns a BoundingInfo
  18207. */
  18208. AbstractMesh.prototype.getBoundingInfo = function () {
  18209. if (this._masterMesh) {
  18210. return this._masterMesh.getBoundingInfo();
  18211. }
  18212. if (!this._boundingInfo) {
  18213. // this._boundingInfo is being created here
  18214. this._updateBoundingInfo();
  18215. }
  18216. // cannot be null.
  18217. return this._boundingInfo;
  18218. };
  18219. /**
  18220. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18221. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18222. */
  18223. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18224. if (includeDescendants === void 0) { includeDescendants = true; }
  18225. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18226. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18227. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18228. if (maxDimension === 0) {
  18229. return this;
  18230. }
  18231. var scale = 1 / maxDimension;
  18232. this.scaling.scaleInPlace(scale);
  18233. return this;
  18234. };
  18235. /**
  18236. * Sets a mesh new object BoundingInfo.
  18237. * Returns the AbstractMesh.
  18238. */
  18239. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18240. this._boundingInfo = boundingInfo;
  18241. return this;
  18242. };
  18243. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18244. get: function () {
  18245. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18246. },
  18247. enumerable: true,
  18248. configurable: true
  18249. });
  18250. AbstractMesh.prototype._preActivate = function () {
  18251. };
  18252. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18253. };
  18254. AbstractMesh.prototype._activate = function (renderId) {
  18255. this._renderId = renderId;
  18256. };
  18257. /**
  18258. * Returns the latest update of the World matrix
  18259. * Returns a Matrix.
  18260. */
  18261. AbstractMesh.prototype.getWorldMatrix = function () {
  18262. if (this._masterMesh) {
  18263. return this._masterMesh.getWorldMatrix();
  18264. }
  18265. return _super.prototype.getWorldMatrix.call(this);
  18266. };
  18267. /**
  18268. * Returns the latest update of the World matrix determinant.
  18269. */
  18270. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18271. if (this._masterMesh) {
  18272. return this._masterMesh._getWorldMatrixDeterminant();
  18273. }
  18274. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18275. };
  18276. // ================================== Point of View Movement =================================
  18277. /**
  18278. * Perform relative position change from the point of view of behind the front of the mesh.
  18279. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18280. * Supports definition of mesh facing forward or backward.
  18281. * @param {number} amountRight
  18282. * @param {number} amountUp
  18283. * @param {number} amountForward
  18284. *
  18285. * Returns the AbstractMesh.
  18286. */
  18287. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18288. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18289. return this;
  18290. };
  18291. /**
  18292. * Calculate relative position change from the point of view of behind the front of the mesh.
  18293. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18294. * Supports definition of mesh facing forward or backward.
  18295. * @param {number} amountRight
  18296. * @param {number} amountUp
  18297. * @param {number} amountForward
  18298. *
  18299. * Returns a new Vector3.
  18300. */
  18301. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18302. var rotMatrix = new BABYLON.Matrix();
  18303. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18304. rotQuaternion.toRotationMatrix(rotMatrix);
  18305. var translationDelta = BABYLON.Vector3.Zero();
  18306. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18307. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18308. return translationDelta;
  18309. };
  18310. // ================================== Point of View Rotation =================================
  18311. /**
  18312. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18313. * Supports definition of mesh facing forward or backward.
  18314. * @param {number} flipBack
  18315. * @param {number} twirlClockwise
  18316. * @param {number} tiltRight
  18317. *
  18318. * Returns the AbstractMesh.
  18319. */
  18320. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18321. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18322. return this;
  18323. };
  18324. /**
  18325. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18326. * Supports definition of mesh facing forward or backward.
  18327. * @param {number} flipBack
  18328. * @param {number} twirlClockwise
  18329. * @param {number} tiltRight
  18330. *
  18331. * Returns a new Vector3.
  18332. */
  18333. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18334. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18335. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18336. };
  18337. /**
  18338. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18339. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18340. */
  18341. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18342. if (includeDescendants === void 0) { includeDescendants = true; }
  18343. this.computeWorldMatrix(true);
  18344. var min;
  18345. var max;
  18346. var boundingInfo = this.getBoundingInfo();
  18347. if (!this.subMeshes) {
  18348. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18349. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18350. }
  18351. else {
  18352. min = boundingInfo.boundingBox.minimumWorld;
  18353. max = boundingInfo.boundingBox.maximumWorld;
  18354. }
  18355. if (includeDescendants) {
  18356. var descendants = this.getDescendants(false);
  18357. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18358. var descendant = descendants_1[_i];
  18359. var childMesh = descendant;
  18360. childMesh.computeWorldMatrix(true);
  18361. //make sure we have the needed params to get mix and max
  18362. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18363. continue;
  18364. }
  18365. var childBoundingInfo = childMesh.getBoundingInfo();
  18366. var boundingBox = childBoundingInfo.boundingBox;
  18367. var minBox = boundingBox.minimumWorld;
  18368. var maxBox = boundingBox.maximumWorld;
  18369. BABYLON.Tools.CheckExtends(minBox, min, max);
  18370. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18371. }
  18372. }
  18373. return {
  18374. min: min,
  18375. max: max
  18376. };
  18377. };
  18378. /**
  18379. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18380. * Returns the AbstractMesh.
  18381. */
  18382. AbstractMesh.prototype._updateBoundingInfo = function () {
  18383. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18384. this._boundingInfo.update(this.worldMatrixFromCache);
  18385. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18386. return this;
  18387. };
  18388. /**
  18389. * Update a mesh's children BoundingInfo objects only.
  18390. * Returns the AbstractMesh.
  18391. */
  18392. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18393. if (!this.subMeshes) {
  18394. return this;
  18395. }
  18396. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18397. var subMesh = this.subMeshes[subIndex];
  18398. if (!subMesh.IsGlobal) {
  18399. subMesh.updateBoundingInfo(matrix);
  18400. }
  18401. }
  18402. return this;
  18403. };
  18404. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18405. // Bounding info
  18406. this._updateBoundingInfo();
  18407. };
  18408. /**
  18409. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18410. * A mesh is in the frustum if its bounding box intersects the frustum.
  18411. * Boolean returned.
  18412. */
  18413. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18414. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18415. };
  18416. /**
  18417. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18418. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18419. * Boolean returned.
  18420. */
  18421. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18422. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18423. ;
  18424. };
  18425. /**
  18426. * True if the mesh intersects another mesh or a SolidParticle object.
  18427. * 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)
  18428. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18429. * Returns a boolean.
  18430. */
  18431. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18432. if (precise === void 0) { precise = false; }
  18433. if (!this._boundingInfo || !mesh._boundingInfo) {
  18434. return false;
  18435. }
  18436. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18437. return true;
  18438. }
  18439. if (includeDescendants) {
  18440. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18441. var child = _a[_i];
  18442. if (child.intersectsMesh(mesh, precise, true)) {
  18443. return true;
  18444. }
  18445. }
  18446. }
  18447. return false;
  18448. };
  18449. /**
  18450. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18451. * Returns a boolean.
  18452. */
  18453. AbstractMesh.prototype.intersectsPoint = function (point) {
  18454. if (!this._boundingInfo) {
  18455. return false;
  18456. }
  18457. return this._boundingInfo.intersectsPoint(point);
  18458. };
  18459. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18460. return this.physicsImpostor;
  18461. };
  18462. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18463. if (camera === void 0) { camera = null; }
  18464. if (!camera) {
  18465. camera = this.getScene().activeCamera;
  18466. }
  18467. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18468. };
  18469. /**
  18470. * Returns the distance from the mesh to the active camera.
  18471. * Returns a float.
  18472. */
  18473. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18474. if (camera === void 0) { camera = null; }
  18475. if (!camera) {
  18476. camera = this.getScene().activeCamera;
  18477. }
  18478. return this.absolutePosition.subtract(camera.position).length();
  18479. };
  18480. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18481. if (!this.physicsImpostor) {
  18482. return this;
  18483. }
  18484. this.physicsImpostor.applyImpulse(force, contactPoint);
  18485. return this;
  18486. };
  18487. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18488. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18489. return this;
  18490. }
  18491. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18492. mainPivot: pivot1,
  18493. connectedPivot: pivot2,
  18494. nativeParams: options
  18495. });
  18496. return this;
  18497. };
  18498. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18499. // Collisions
  18500. /**
  18501. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18502. * Default `false`.
  18503. */
  18504. get: function () {
  18505. return this._checkCollisions;
  18506. },
  18507. set: function (collisionEnabled) {
  18508. this._checkCollisions = collisionEnabled;
  18509. if (this.getScene().workerCollisions) {
  18510. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18511. }
  18512. },
  18513. enumerable: true,
  18514. configurable: true
  18515. });
  18516. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18517. /**
  18518. * Gets Collider object used to compute collisions (not physics)
  18519. */
  18520. get: function () {
  18521. return this._collider;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18527. var globalPosition = this.getAbsolutePosition();
  18528. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18529. if (!this._collider) {
  18530. this._collider = new BABYLON.Collider();
  18531. }
  18532. this._collider._radius = this.ellipsoid;
  18533. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18534. return this;
  18535. };
  18536. // Submeshes octree
  18537. /**
  18538. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18539. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18540. * Returns an Octree of submeshes.
  18541. */
  18542. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18543. if (maxCapacity === void 0) { maxCapacity = 64; }
  18544. if (maxDepth === void 0) { maxDepth = 2; }
  18545. if (!this._submeshesOctree) {
  18546. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18547. }
  18548. this.computeWorldMatrix(true);
  18549. var boundingInfo = this.getBoundingInfo();
  18550. // Update octree
  18551. var bbox = boundingInfo.boundingBox;
  18552. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18553. return this._submeshesOctree;
  18554. };
  18555. // Collisions
  18556. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18557. this._generatePointsArray();
  18558. if (!this._positions) {
  18559. return this;
  18560. }
  18561. // Transformation
  18562. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18563. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18564. subMesh._lastColliderWorldVertices = [];
  18565. subMesh._trianglePlanes = [];
  18566. var start = subMesh.verticesStart;
  18567. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18568. for (var i = start; i < end; i++) {
  18569. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18570. }
  18571. }
  18572. // Collide
  18573. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18574. if (collider.collisionFound) {
  18575. collider.collidedMesh = this;
  18576. }
  18577. return this;
  18578. };
  18579. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18580. var subMeshes;
  18581. var len;
  18582. // Octrees
  18583. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18584. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18585. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18586. len = intersections.length;
  18587. subMeshes = intersections.data;
  18588. }
  18589. else {
  18590. subMeshes = this.subMeshes;
  18591. len = subMeshes.length;
  18592. }
  18593. for (var index = 0; index < len; index++) {
  18594. var subMesh = subMeshes[index];
  18595. // Bounding test
  18596. if (len > 1 && !subMesh._checkCollision(collider))
  18597. continue;
  18598. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18599. }
  18600. return this;
  18601. };
  18602. AbstractMesh.prototype._checkCollision = function (collider) {
  18603. // Bounding box test
  18604. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18605. return this;
  18606. // Transformation matrix
  18607. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18608. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18609. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18610. return this;
  18611. };
  18612. // Picking
  18613. AbstractMesh.prototype._generatePointsArray = function () {
  18614. return false;
  18615. };
  18616. /**
  18617. * Checks if the passed Ray intersects with the mesh.
  18618. * Returns an object PickingInfo.
  18619. */
  18620. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18621. var pickingInfo = new BABYLON.PickingInfo();
  18622. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18623. return pickingInfo;
  18624. }
  18625. if (!this._generatePointsArray()) {
  18626. return pickingInfo;
  18627. }
  18628. var intersectInfo = null;
  18629. // Octrees
  18630. var subMeshes;
  18631. var len;
  18632. if (this._submeshesOctree && this.useOctreeForPicking) {
  18633. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18634. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18635. len = intersections.length;
  18636. subMeshes = intersections.data;
  18637. }
  18638. else {
  18639. subMeshes = this.subMeshes;
  18640. len = subMeshes.length;
  18641. }
  18642. for (var index = 0; index < len; index++) {
  18643. var subMesh = subMeshes[index];
  18644. // Bounding test
  18645. if (len > 1 && !subMesh.canIntersects(ray))
  18646. continue;
  18647. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18648. if (currentIntersectInfo) {
  18649. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18650. intersectInfo = currentIntersectInfo;
  18651. intersectInfo.subMeshId = index;
  18652. if (fastCheck) {
  18653. break;
  18654. }
  18655. }
  18656. }
  18657. }
  18658. if (intersectInfo) {
  18659. // Get picked point
  18660. var world = this.getWorldMatrix();
  18661. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18662. var direction = ray.direction.clone();
  18663. direction = direction.scale(intersectInfo.distance);
  18664. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18665. var pickedPoint = worldOrigin.add(worldDirection);
  18666. // Return result
  18667. pickingInfo.hit = true;
  18668. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18669. pickingInfo.pickedPoint = pickedPoint;
  18670. pickingInfo.pickedMesh = this;
  18671. pickingInfo.bu = intersectInfo.bu || 0;
  18672. pickingInfo.bv = intersectInfo.bv || 0;
  18673. pickingInfo.faceId = intersectInfo.faceId;
  18674. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18675. return pickingInfo;
  18676. }
  18677. return pickingInfo;
  18678. };
  18679. /**
  18680. * Clones the mesh, used by the class Mesh.
  18681. * Just returns `null` for an AbstractMesh.
  18682. */
  18683. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18684. return null;
  18685. };
  18686. /**
  18687. * Disposes all the mesh submeshes.
  18688. * Returns the AbstractMesh.
  18689. */
  18690. AbstractMesh.prototype.releaseSubMeshes = function () {
  18691. if (this.subMeshes) {
  18692. while (this.subMeshes.length) {
  18693. this.subMeshes[0].dispose();
  18694. }
  18695. }
  18696. else {
  18697. this.subMeshes = new Array();
  18698. }
  18699. return this;
  18700. };
  18701. /**
  18702. * Releases resources associated with this abstract mesh.
  18703. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18704. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18705. */
  18706. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18707. var _this = this;
  18708. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18709. var index;
  18710. // Smart Array Retainers.
  18711. this.getScene().freeActiveMeshes();
  18712. this.getScene().freeRenderingGroups();
  18713. // Action manager
  18714. if (this.actionManager !== undefined && this.actionManager !== null) {
  18715. this.actionManager.dispose();
  18716. this.actionManager = null;
  18717. }
  18718. // Skeleton
  18719. this._skeleton = null;
  18720. // Physics
  18721. if (this.physicsImpostor) {
  18722. this.physicsImpostor.dispose();
  18723. }
  18724. // Intersections in progress
  18725. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18726. var other = this._intersectionsInProgress[index];
  18727. var pos = other._intersectionsInProgress.indexOf(this);
  18728. other._intersectionsInProgress.splice(pos, 1);
  18729. }
  18730. this._intersectionsInProgress = [];
  18731. // Lights
  18732. var lights = this.getScene().lights;
  18733. lights.forEach(function (light) {
  18734. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18735. if (meshIndex !== -1) {
  18736. light.includedOnlyMeshes.splice(meshIndex, 1);
  18737. }
  18738. meshIndex = light.excludedMeshes.indexOf(_this);
  18739. if (meshIndex !== -1) {
  18740. light.excludedMeshes.splice(meshIndex, 1);
  18741. }
  18742. // Shadow generators
  18743. var generator = light.getShadowGenerator();
  18744. if (generator) {
  18745. var shadowMap = generator.getShadowMap();
  18746. if (shadowMap && shadowMap.renderList) {
  18747. meshIndex = shadowMap.renderList.indexOf(_this);
  18748. if (meshIndex !== -1) {
  18749. shadowMap.renderList.splice(meshIndex, 1);
  18750. }
  18751. }
  18752. }
  18753. });
  18754. // Edges
  18755. if (this._edgesRenderer) {
  18756. this._edgesRenderer.dispose();
  18757. this._edgesRenderer = null;
  18758. }
  18759. // SubMeshes
  18760. if (this.getClassName() !== "InstancedMesh") {
  18761. this.releaseSubMeshes();
  18762. }
  18763. // Octree
  18764. var sceneOctree = this.getScene().selectionOctree;
  18765. if (sceneOctree !== undefined && sceneOctree !== null) {
  18766. var index = sceneOctree.dynamicContent.indexOf(this);
  18767. if (index !== -1) {
  18768. sceneOctree.dynamicContent.splice(index, 1);
  18769. }
  18770. }
  18771. // Query
  18772. var engine = this.getScene().getEngine();
  18773. if (this._occlusionQuery) {
  18774. this._isOcclusionQueryInProgress = false;
  18775. engine.deleteQuery(this._occlusionQuery);
  18776. this._occlusionQuery = null;
  18777. }
  18778. // Engine
  18779. engine.wipeCaches();
  18780. // Remove from scene
  18781. this.getScene().removeMesh(this);
  18782. if (disposeMaterialAndTextures) {
  18783. if (this.material) {
  18784. this.material.dispose(false, true);
  18785. }
  18786. }
  18787. if (!doNotRecurse) {
  18788. // Particles
  18789. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18790. if (this.getScene().particleSystems[index].emitter === this) {
  18791. this.getScene().particleSystems[index].dispose();
  18792. index--;
  18793. }
  18794. }
  18795. }
  18796. // facet data
  18797. if (this._facetDataEnabled) {
  18798. this.disableFacetData();
  18799. }
  18800. this.onAfterWorldMatrixUpdateObservable.clear();
  18801. this.onCollideObservable.clear();
  18802. this.onCollisionPositionChangeObservable.clear();
  18803. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18804. };
  18805. /**
  18806. * Adds the passed mesh as a child to the current mesh.
  18807. * Returns the AbstractMesh.
  18808. */
  18809. AbstractMesh.prototype.addChild = function (mesh) {
  18810. mesh.setParent(this);
  18811. return this;
  18812. };
  18813. /**
  18814. * Removes the passed mesh from the current mesh children list.
  18815. * Returns the AbstractMesh.
  18816. */
  18817. AbstractMesh.prototype.removeChild = function (mesh) {
  18818. mesh.setParent(null);
  18819. return this;
  18820. };
  18821. // Facet data
  18822. /**
  18823. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18824. * Returns the AbstractMesh.
  18825. */
  18826. AbstractMesh.prototype._initFacetData = function () {
  18827. if (!this._facetNormals) {
  18828. this._facetNormals = new Array();
  18829. }
  18830. if (!this._facetPositions) {
  18831. this._facetPositions = new Array();
  18832. }
  18833. if (!this._facetPartitioning) {
  18834. this._facetPartitioning = new Array();
  18835. }
  18836. this._facetNb = (this.getIndices().length / 3) | 0;
  18837. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18838. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18839. for (var f = 0; f < this._facetNb; f++) {
  18840. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18841. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18842. }
  18843. this._facetDataEnabled = true;
  18844. return this;
  18845. };
  18846. /**
  18847. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18848. * This method can be called within the render loop.
  18849. * 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.
  18850. * Returns the AbstractMesh.
  18851. */
  18852. AbstractMesh.prototype.updateFacetData = function () {
  18853. if (!this._facetDataEnabled) {
  18854. this._initFacetData();
  18855. }
  18856. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18857. var indices = this.getIndices();
  18858. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18859. var bInfo = this.getBoundingInfo();
  18860. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18861. // init arrays, matrix and sort function on first call
  18862. this._facetDepthSortEnabled = true;
  18863. if (indices instanceof Uint16Array) {
  18864. this._depthSortedIndices = new Uint16Array(indices);
  18865. }
  18866. else if (indices instanceof Uint32Array) {
  18867. this._depthSortedIndices = new Uint32Array(indices);
  18868. }
  18869. else {
  18870. var needs32bits = false;
  18871. for (var i = 0; i < indices.length; i++) {
  18872. if (indices[i] > 65535) {
  18873. needs32bits = true;
  18874. break;
  18875. }
  18876. }
  18877. if (needs32bits) {
  18878. this._depthSortedIndices = new Uint32Array(indices);
  18879. }
  18880. else {
  18881. this._depthSortedIndices = new Uint16Array(indices);
  18882. }
  18883. }
  18884. this._facetDepthSortFunction = function (f1, f2) {
  18885. return (f2.sqDistance - f1.sqDistance);
  18886. };
  18887. if (!this._facetDepthSortFrom) {
  18888. var camera = this.getScene().activeCamera;
  18889. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18890. }
  18891. this._depthSortedFacets = [];
  18892. for (var f = 0; f < this._facetNb; f++) {
  18893. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18894. this._depthSortedFacets.push(depthSortedFacet);
  18895. }
  18896. this._invertedMatrix = BABYLON.Matrix.Identity();
  18897. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18898. }
  18899. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18900. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18901. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18902. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18903. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18904. this._subDiv.max = this._partitioningSubdivisions;
  18905. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18906. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18907. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18908. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18909. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18910. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18911. // set the parameters for ComputeNormals()
  18912. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18913. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18914. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18915. this._facetParameters.bInfo = bInfo;
  18916. this._facetParameters.bbSize = this._bbSize;
  18917. this._facetParameters.subDiv = this._subDiv;
  18918. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18919. this._facetParameters.depthSort = this._facetDepthSort;
  18920. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18921. this.computeWorldMatrix(true);
  18922. this._worldMatrix.invertToRef(this._invertedMatrix);
  18923. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18924. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18925. }
  18926. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18927. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18928. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18929. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18930. var l = (this._depthSortedIndices.length / 3) | 0;
  18931. for (var f = 0; f < l; f++) {
  18932. var sind = this._depthSortedFacets[f].ind;
  18933. this._depthSortedIndices[f * 3] = indices[sind];
  18934. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18935. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18936. }
  18937. this.updateIndices(this._depthSortedIndices);
  18938. }
  18939. return this;
  18940. };
  18941. /**
  18942. * Returns the facetLocalNormals array.
  18943. * The normals are expressed in the mesh local space.
  18944. */
  18945. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18946. if (!this._facetNormals) {
  18947. this.updateFacetData();
  18948. }
  18949. return this._facetNormals;
  18950. };
  18951. /**
  18952. * Returns the facetLocalPositions array.
  18953. * The facet positions are expressed in the mesh local space.
  18954. */
  18955. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18956. if (!this._facetPositions) {
  18957. this.updateFacetData();
  18958. }
  18959. return this._facetPositions;
  18960. };
  18961. /**
  18962. * Returns the facetLocalPartioning array.
  18963. */
  18964. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18965. if (!this._facetPartitioning) {
  18966. this.updateFacetData();
  18967. }
  18968. return this._facetPartitioning;
  18969. };
  18970. /**
  18971. * Returns the i-th facet position in the world system.
  18972. * This method allocates a new Vector3 per call.
  18973. */
  18974. AbstractMesh.prototype.getFacetPosition = function (i) {
  18975. var pos = BABYLON.Vector3.Zero();
  18976. this.getFacetPositionToRef(i, pos);
  18977. return pos;
  18978. };
  18979. /**
  18980. * Sets the reference Vector3 with the i-th facet position in the world system.
  18981. * Returns the AbstractMesh.
  18982. */
  18983. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18984. var localPos = (this.getFacetLocalPositions())[i];
  18985. var world = this.getWorldMatrix();
  18986. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18987. return this;
  18988. };
  18989. /**
  18990. * Returns the i-th facet normal in the world system.
  18991. * This method allocates a new Vector3 per call.
  18992. */
  18993. AbstractMesh.prototype.getFacetNormal = function (i) {
  18994. var norm = BABYLON.Vector3.Zero();
  18995. this.getFacetNormalToRef(i, norm);
  18996. return norm;
  18997. };
  18998. /**
  18999. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19000. * Returns the AbstractMesh.
  19001. */
  19002. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19003. var localNorm = (this.getFacetLocalNormals())[i];
  19004. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19005. return this;
  19006. };
  19007. /**
  19008. * 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).
  19009. */
  19010. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19011. var bInfo = this.getBoundingInfo();
  19012. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19013. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19014. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19015. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19016. return null;
  19017. }
  19018. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19019. };
  19020. /**
  19021. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19022. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19023. * If checkFace is 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.
  19024. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19025. * 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.
  19026. */
  19027. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19028. if (checkFace === void 0) { checkFace = false; }
  19029. if (facing === void 0) { facing = true; }
  19030. var world = this.getWorldMatrix();
  19031. var invMat = BABYLON.Tmp.Matrix[5];
  19032. world.invertToRef(invMat);
  19033. var invVect = BABYLON.Tmp.Vector3[8];
  19034. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19035. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19036. if (projected) {
  19037. // tranform the local computed projected vector to world coordinates
  19038. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19039. }
  19040. return closest;
  19041. };
  19042. /**
  19043. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19044. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19045. * If checkFace is 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.
  19046. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19047. * 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.
  19048. */
  19049. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19050. if (checkFace === void 0) { checkFace = false; }
  19051. if (facing === void 0) { facing = true; }
  19052. var closest = null;
  19053. var tmpx = 0.0;
  19054. var tmpy = 0.0;
  19055. var tmpz = 0.0;
  19056. var d = 0.0; // tmp dot facet normal * facet position
  19057. var t0 = 0.0;
  19058. var projx = 0.0;
  19059. var projy = 0.0;
  19060. var projz = 0.0;
  19061. // Get all the facets in the same partitioning block than (x, y, z)
  19062. var facetPositions = this.getFacetLocalPositions();
  19063. var facetNormals = this.getFacetLocalNormals();
  19064. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19065. if (!facetsInBlock) {
  19066. return null;
  19067. }
  19068. // Get the closest facet to (x, y, z)
  19069. var shortest = Number.MAX_VALUE; // init distance vars
  19070. var tmpDistance = shortest;
  19071. var fib; // current facet in the block
  19072. var norm; // current facet normal
  19073. var p0; // current facet barycenter position
  19074. // loop on all the facets in the current partitioning block
  19075. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19076. fib = facetsInBlock[idx];
  19077. norm = facetNormals[fib];
  19078. p0 = facetPositions[fib];
  19079. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19080. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19081. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19082. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19083. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19084. projx = x + norm.x * t0;
  19085. projy = y + norm.y * t0;
  19086. projz = z + norm.z * t0;
  19087. tmpx = projx - x;
  19088. tmpy = projy - y;
  19089. tmpz = projz - z;
  19090. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19091. if (tmpDistance < shortest) {
  19092. shortest = tmpDistance;
  19093. closest = fib;
  19094. if (projected) {
  19095. projected.x = projx;
  19096. projected.y = projy;
  19097. projected.z = projz;
  19098. }
  19099. }
  19100. }
  19101. }
  19102. return closest;
  19103. };
  19104. /**
  19105. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19106. */
  19107. AbstractMesh.prototype.getFacetDataParameters = function () {
  19108. return this._facetParameters;
  19109. };
  19110. /**
  19111. * Disables the feature FacetData and frees the related memory.
  19112. * Returns the AbstractMesh.
  19113. */
  19114. AbstractMesh.prototype.disableFacetData = function () {
  19115. if (this._facetDataEnabled) {
  19116. this._facetDataEnabled = false;
  19117. this._facetPositions = new Array();
  19118. this._facetNormals = new Array();
  19119. this._facetPartitioning = new Array();
  19120. this._facetParameters = null;
  19121. this._depthSortedIndices = new Uint32Array(0);
  19122. }
  19123. return this;
  19124. };
  19125. /**
  19126. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19127. * Returns the mesh.
  19128. */
  19129. AbstractMesh.prototype.updateIndices = function (indices) {
  19130. return this;
  19131. };
  19132. /**
  19133. * The mesh Geometry. Actually used by the Mesh object.
  19134. * Returns a blank geometry object.
  19135. */
  19136. /**
  19137. * Creates new normals data for the mesh.
  19138. * @param updatable.
  19139. */
  19140. AbstractMesh.prototype.createNormals = function (updatable) {
  19141. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19142. var indices = this.getIndices();
  19143. var normals;
  19144. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19145. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19146. }
  19147. else {
  19148. normals = [];
  19149. }
  19150. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19151. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19152. };
  19153. /**
  19154. * Align the mesh with a normal.
  19155. * Returns the mesh.
  19156. */
  19157. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19158. if (!upDirection) {
  19159. upDirection = BABYLON.Axis.Y;
  19160. }
  19161. var axisX = BABYLON.Tmp.Vector3[0];
  19162. var axisZ = BABYLON.Tmp.Vector3[1];
  19163. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19164. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19165. if (this.rotationQuaternion) {
  19166. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19167. }
  19168. else {
  19169. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19170. }
  19171. return this;
  19172. };
  19173. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19174. var engine = this.getEngine();
  19175. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19176. this._isOccluded = false;
  19177. return;
  19178. }
  19179. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19180. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19181. if (isOcclusionQueryAvailable) {
  19182. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19183. this._isOcclusionQueryInProgress = false;
  19184. this._occlusionInternalRetryCounter = 0;
  19185. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19186. }
  19187. else {
  19188. this._occlusionInternalRetryCounter++;
  19189. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19190. this._isOcclusionQueryInProgress = false;
  19191. this._occlusionInternalRetryCounter = 0;
  19192. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19193. // if strict continue the last state of the object.
  19194. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19195. }
  19196. else {
  19197. return;
  19198. }
  19199. }
  19200. }
  19201. var scene = this.getScene();
  19202. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19203. if (!this._occlusionQuery) {
  19204. this._occlusionQuery = engine.createQuery();
  19205. }
  19206. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19207. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19208. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19209. this._isOcclusionQueryInProgress = true;
  19210. };
  19211. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19212. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19213. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19214. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19215. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19216. return AbstractMesh;
  19217. }(BABYLON.TransformNode));
  19218. BABYLON.AbstractMesh = AbstractMesh;
  19219. })(BABYLON || (BABYLON = {}));
  19220. //# sourceMappingURL=babylon.abstractMesh.js.map
  19221. "use strict";
  19222. var BABYLON;
  19223. (function (BABYLON) {
  19224. /**
  19225. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19226. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19227. * 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.
  19228. */
  19229. var Light = /** @class */ (function (_super) {
  19230. __extends(Light, _super);
  19231. /**
  19232. * Creates a Light object in the scene.
  19233. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19234. * @param name The firendly name of the light
  19235. * @param scene The scene the light belongs too
  19236. */
  19237. function Light(name, scene) {
  19238. var _this = _super.call(this, name, scene) || this;
  19239. /**
  19240. * Diffuse gives the basic color to an object.
  19241. */
  19242. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19243. /**
  19244. * Specular produces a highlight color on an object.
  19245. * Note: This is note affecting PBR materials.
  19246. */
  19247. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19248. /**
  19249. * Strength of the light.
  19250. * Note: By default it is define in the framework own unit.
  19251. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19252. */
  19253. _this.intensity = 1.0;
  19254. /**
  19255. * Defines how far from the source the light is impacting in scene units.
  19256. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19257. */
  19258. _this.range = Number.MAX_VALUE;
  19259. /**
  19260. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19261. * of light.
  19262. */
  19263. _this._photometricScale = 1.0;
  19264. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19265. _this._radius = 0.00001;
  19266. /**
  19267. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19268. * exceeding the number allowed of the materials.
  19269. */
  19270. _this.renderPriority = 0;
  19271. /**
  19272. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19273. * the current shadow generator.
  19274. */
  19275. _this.shadowEnabled = true;
  19276. _this._excludeWithLayerMask = 0;
  19277. _this._includeOnlyWithLayerMask = 0;
  19278. _this._lightmapMode = 0;
  19279. /**
  19280. * @ignore Internal use only.
  19281. */
  19282. _this._excludedMeshesIds = new Array();
  19283. /**
  19284. * @ignore Internal use only.
  19285. */
  19286. _this._includedOnlyMeshesIds = new Array();
  19287. _this.getScene().addLight(_this);
  19288. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19289. _this._buildUniformLayout();
  19290. _this.includedOnlyMeshes = new Array();
  19291. _this.excludedMeshes = new Array();
  19292. _this._resyncMeshes();
  19293. return _this;
  19294. }
  19295. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19296. /**
  19297. * If every light affecting the material is in this lightmapMode,
  19298. * material.lightmapTexture adds or multiplies
  19299. * (depends on material.useLightmapAsShadowmap)
  19300. * after every other light calculations.
  19301. */
  19302. get: function () {
  19303. return Light._LIGHTMAP_DEFAULT;
  19304. },
  19305. enumerable: true,
  19306. configurable: true
  19307. });
  19308. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19309. /**
  19310. * material.lightmapTexture as only diffuse lighting from this light
  19311. * adds only specular lighting from this light
  19312. * adds dynamic shadows
  19313. */
  19314. get: function () {
  19315. return Light._LIGHTMAP_SPECULAR;
  19316. },
  19317. enumerable: true,
  19318. configurable: true
  19319. });
  19320. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19321. /**
  19322. * material.lightmapTexture as only lighting
  19323. * no light calculation from this light
  19324. * only adds dynamic shadows from this light
  19325. */
  19326. get: function () {
  19327. return Light._LIGHTMAP_SHADOWSONLY;
  19328. },
  19329. enumerable: true,
  19330. configurable: true
  19331. });
  19332. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19333. /**
  19334. * Each light type uses the default quantity according to its type:
  19335. * point/spot lights use luminous intensity
  19336. * directional lights use illuminance
  19337. */
  19338. get: function () {
  19339. return Light._INTENSITYMODE_AUTOMATIC;
  19340. },
  19341. enumerable: true,
  19342. configurable: true
  19343. });
  19344. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19345. /**
  19346. * lumen (lm)
  19347. */
  19348. get: function () {
  19349. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19350. },
  19351. enumerable: true,
  19352. configurable: true
  19353. });
  19354. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19355. /**
  19356. * candela (lm/sr)
  19357. */
  19358. get: function () {
  19359. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19365. /**
  19366. * lux (lm/m^2)
  19367. */
  19368. get: function () {
  19369. return Light._INTENSITYMODE_ILLUMINANCE;
  19370. },
  19371. enumerable: true,
  19372. configurable: true
  19373. });
  19374. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19375. /**
  19376. * nit (cd/m^2)
  19377. */
  19378. get: function () {
  19379. return Light._INTENSITYMODE_LUMINANCE;
  19380. },
  19381. enumerable: true,
  19382. configurable: true
  19383. });
  19384. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19385. /**
  19386. * Light type const id of the point light.
  19387. */
  19388. get: function () {
  19389. return Light._LIGHTTYPEID_POINTLIGHT;
  19390. },
  19391. enumerable: true,
  19392. configurable: true
  19393. });
  19394. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19395. /**
  19396. * Light type const id of the directional light.
  19397. */
  19398. get: function () {
  19399. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19400. },
  19401. enumerable: true,
  19402. configurable: true
  19403. });
  19404. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19405. /**
  19406. * Light type const id of the spot light.
  19407. */
  19408. get: function () {
  19409. return Light._LIGHTTYPEID_SPOTLIGHT;
  19410. },
  19411. enumerable: true,
  19412. configurable: true
  19413. });
  19414. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19415. /**
  19416. * Light type const id of the hemispheric light.
  19417. */
  19418. get: function () {
  19419. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. Object.defineProperty(Light.prototype, "intensityMode", {
  19425. /**
  19426. * Gets the photometric scale used to interpret the intensity.
  19427. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19428. */
  19429. get: function () {
  19430. return this._intensityMode;
  19431. },
  19432. /**
  19433. * Sets the photometric scale used to interpret the intensity.
  19434. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19435. */
  19436. set: function (value) {
  19437. this._intensityMode = value;
  19438. this._computePhotometricScale();
  19439. },
  19440. enumerable: true,
  19441. configurable: true
  19442. });
  19443. ;
  19444. ;
  19445. Object.defineProperty(Light.prototype, "radius", {
  19446. /**
  19447. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19448. */
  19449. get: function () {
  19450. return this._radius;
  19451. },
  19452. /**
  19453. * sets the light radius used by PBR Materials to simulate soft area lights.
  19454. */
  19455. set: function (value) {
  19456. this._radius = value;
  19457. this._computePhotometricScale();
  19458. },
  19459. enumerable: true,
  19460. configurable: true
  19461. });
  19462. ;
  19463. ;
  19464. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19465. /**
  19466. * Gets the only meshes impacted by this light.
  19467. */
  19468. get: function () {
  19469. return this._includedOnlyMeshes;
  19470. },
  19471. /**
  19472. * Sets the only meshes impacted by this light.
  19473. */
  19474. set: function (value) {
  19475. this._includedOnlyMeshes = value;
  19476. this._hookArrayForIncludedOnly(value);
  19477. },
  19478. enumerable: true,
  19479. configurable: true
  19480. });
  19481. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19482. /**
  19483. * Gets the meshes not impacted by this light.
  19484. */
  19485. get: function () {
  19486. return this._excludedMeshes;
  19487. },
  19488. /**
  19489. * Sets the meshes not impacted by this light.
  19490. */
  19491. set: function (value) {
  19492. this._excludedMeshes = value;
  19493. this._hookArrayForExcluded(value);
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19499. /**
  19500. * Gets the layer id use to find what meshes are not impacted by the light.
  19501. * Inactive if 0
  19502. */
  19503. get: function () {
  19504. return this._excludeWithLayerMask;
  19505. },
  19506. /**
  19507. * Sets the layer id use to find what meshes are not impacted by the light.
  19508. * Inactive if 0
  19509. */
  19510. set: function (value) {
  19511. this._excludeWithLayerMask = value;
  19512. this._resyncMeshes();
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19518. /**
  19519. * Gets the layer id use to find what meshes are impacted by the light.
  19520. * Inactive if 0
  19521. */
  19522. get: function () {
  19523. return this._includeOnlyWithLayerMask;
  19524. },
  19525. /**
  19526. * Sets the layer id use to find what meshes are impacted by the light.
  19527. * Inactive if 0
  19528. */
  19529. set: function (value) {
  19530. this._includeOnlyWithLayerMask = value;
  19531. this._resyncMeshes();
  19532. },
  19533. enumerable: true,
  19534. configurable: true
  19535. });
  19536. Object.defineProperty(Light.prototype, "lightmapMode", {
  19537. /**
  19538. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19539. */
  19540. get: function () {
  19541. return this._lightmapMode;
  19542. },
  19543. /**
  19544. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19545. */
  19546. set: function (value) {
  19547. if (this._lightmapMode === value) {
  19548. return;
  19549. }
  19550. this._lightmapMode = value;
  19551. this._markMeshesAsLightDirty();
  19552. },
  19553. enumerable: true,
  19554. configurable: true
  19555. });
  19556. /**
  19557. * Returns the string "Light".
  19558. * @returns the class name
  19559. */
  19560. Light.prototype.getClassName = function () {
  19561. return "Light";
  19562. };
  19563. /**
  19564. * Converts the light information to a readable string for debug purpose.
  19565. * @param fullDetails Supports for multiple levels of logging within scene loading
  19566. * @returns the human readable light info
  19567. */
  19568. Light.prototype.toString = function (fullDetails) {
  19569. var ret = "Name: " + this.name;
  19570. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19571. if (this.animations) {
  19572. for (var i = 0; i < this.animations.length; i++) {
  19573. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19574. }
  19575. }
  19576. if (fullDetails) {
  19577. }
  19578. return ret;
  19579. };
  19580. /**
  19581. * Set the enabled state of this node.
  19582. * @param value - the new enabled state
  19583. */
  19584. Light.prototype.setEnabled = function (value) {
  19585. _super.prototype.setEnabled.call(this, value);
  19586. this._resyncMeshes();
  19587. };
  19588. /**
  19589. * Returns the Light associated shadow generator if any.
  19590. * @return the associated shadow generator.
  19591. */
  19592. Light.prototype.getShadowGenerator = function () {
  19593. return this._shadowGenerator;
  19594. };
  19595. /**
  19596. * Returns a Vector3, the absolute light position in the World.
  19597. * @returns the world space position of the light
  19598. */
  19599. Light.prototype.getAbsolutePosition = function () {
  19600. return BABYLON.Vector3.Zero();
  19601. };
  19602. /**
  19603. * Specifies if the light will affect the passed mesh.
  19604. * @param mesh The mesh to test against the light
  19605. * @return true the mesh is affected otherwise, false.
  19606. */
  19607. Light.prototype.canAffectMesh = function (mesh) {
  19608. if (!mesh) {
  19609. return true;
  19610. }
  19611. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19612. return false;
  19613. }
  19614. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19615. return false;
  19616. }
  19617. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19618. return false;
  19619. }
  19620. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19621. return false;
  19622. }
  19623. return true;
  19624. };
  19625. /**
  19626. * Computes and Returns the light World matrix.
  19627. * @returns the world matrix
  19628. */
  19629. Light.prototype.getWorldMatrix = function () {
  19630. this._currentRenderId = this.getScene().getRenderId();
  19631. var worldMatrix = this._getWorldMatrix();
  19632. if (this.parent && this.parent.getWorldMatrix) {
  19633. if (!this._parentedWorldMatrix) {
  19634. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19635. }
  19636. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19637. this._markSyncedWithParent();
  19638. return this._parentedWorldMatrix;
  19639. }
  19640. return worldMatrix;
  19641. };
  19642. /**
  19643. * Sort function to order lights for rendering.
  19644. * @param a First Light object to compare to second.
  19645. * @param b Second Light object to compare first.
  19646. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19647. */
  19648. Light.CompareLightsPriority = function (a, b) {
  19649. //shadow-casting lights have priority over non-shadow-casting lights
  19650. //the renderPrioirty is a secondary sort criterion
  19651. if (a.shadowEnabled !== b.shadowEnabled) {
  19652. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19653. }
  19654. return b.renderPriority - a.renderPriority;
  19655. };
  19656. /**
  19657. * Releases resources associated with this node.
  19658. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19659. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19660. */
  19661. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19662. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19663. if (this._shadowGenerator) {
  19664. this._shadowGenerator.dispose();
  19665. this._shadowGenerator = null;
  19666. }
  19667. // Animations
  19668. this.getScene().stopAnimation(this);
  19669. // Remove from meshes
  19670. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19671. var mesh = _a[_i];
  19672. mesh._removeLightSource(this);
  19673. }
  19674. this._uniformBuffer.dispose();
  19675. // Remove from scene
  19676. this.getScene().removeLight(this);
  19677. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19678. };
  19679. /**
  19680. * Returns the light type ID (integer).
  19681. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19682. */
  19683. Light.prototype.getTypeID = function () {
  19684. return 0;
  19685. };
  19686. /**
  19687. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19688. * @returns the scaled intensity in intensity mode unit
  19689. */
  19690. Light.prototype.getScaledIntensity = function () {
  19691. return this._photometricScale * this.intensity;
  19692. };
  19693. /**
  19694. * Returns a new Light object, named "name", from the current one.
  19695. * @param name The name of the cloned light
  19696. * @returns the new created light
  19697. */
  19698. Light.prototype.clone = function (name) {
  19699. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19700. if (!constructor) {
  19701. return null;
  19702. }
  19703. return BABYLON.SerializationHelper.Clone(constructor, this);
  19704. };
  19705. /**
  19706. * Serializes the current light into a Serialization object.
  19707. * @returns the serialized object.
  19708. */
  19709. Light.prototype.serialize = function () {
  19710. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19711. // Type
  19712. serializationObject.type = this.getTypeID();
  19713. // Parent
  19714. if (this.parent) {
  19715. serializationObject.parentId = this.parent.id;
  19716. }
  19717. // Inclusion / exclusions
  19718. if (this.excludedMeshes.length > 0) {
  19719. serializationObject.excludedMeshesIds = [];
  19720. this.excludedMeshes.forEach(function (mesh) {
  19721. serializationObject.excludedMeshesIds.push(mesh.id);
  19722. });
  19723. }
  19724. if (this.includedOnlyMeshes.length > 0) {
  19725. serializationObject.includedOnlyMeshesIds = [];
  19726. this.includedOnlyMeshes.forEach(function (mesh) {
  19727. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19728. });
  19729. }
  19730. // Animations
  19731. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19732. serializationObject.ranges = this.serializeAnimationRanges();
  19733. return serializationObject;
  19734. };
  19735. /**
  19736. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19737. * This new light is named "name" and added to the passed scene.
  19738. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19739. * @param name The friendly name of the light
  19740. * @param scene The scene the new light will belong to
  19741. * @returns the constructor function
  19742. */
  19743. Light.GetConstructorFromName = function (type, name, scene) {
  19744. switch (type) {
  19745. case 0:
  19746. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19747. case 1:
  19748. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19749. case 2:
  19750. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19751. case 3:
  19752. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19753. }
  19754. return null;
  19755. };
  19756. /**
  19757. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19758. * @param parsedLight The JSON representation of the light
  19759. * @param scene The scene to create the parsed light in
  19760. * @returns the created light after parsing
  19761. */
  19762. Light.Parse = function (parsedLight, scene) {
  19763. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19764. if (!constructor) {
  19765. return null;
  19766. }
  19767. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19768. // Inclusion / exclusions
  19769. if (parsedLight.excludedMeshesIds) {
  19770. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19771. }
  19772. if (parsedLight.includedOnlyMeshesIds) {
  19773. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19774. }
  19775. // Parent
  19776. if (parsedLight.parentId) {
  19777. light._waitingParentId = parsedLight.parentId;
  19778. }
  19779. // Animations
  19780. if (parsedLight.animations) {
  19781. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19782. var parsedAnimation = parsedLight.animations[animationIndex];
  19783. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19784. }
  19785. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19786. }
  19787. if (parsedLight.autoAnimate) {
  19788. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19789. }
  19790. return light;
  19791. };
  19792. Light.prototype._hookArrayForExcluded = function (array) {
  19793. var _this = this;
  19794. var oldPush = array.push;
  19795. array.push = function () {
  19796. var items = [];
  19797. for (var _i = 0; _i < arguments.length; _i++) {
  19798. items[_i] = arguments[_i];
  19799. }
  19800. var result = oldPush.apply(array, items);
  19801. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19802. var item = items_1[_a];
  19803. item._resyncLighSource(_this);
  19804. }
  19805. return result;
  19806. };
  19807. var oldSplice = array.splice;
  19808. array.splice = function (index, deleteCount) {
  19809. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19810. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19811. var item = deleted_1[_i];
  19812. item._resyncLighSource(_this);
  19813. }
  19814. return deleted;
  19815. };
  19816. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19817. var item = array_1[_i];
  19818. item._resyncLighSource(this);
  19819. }
  19820. };
  19821. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19822. var _this = this;
  19823. var oldPush = array.push;
  19824. array.push = function () {
  19825. var items = [];
  19826. for (var _i = 0; _i < arguments.length; _i++) {
  19827. items[_i] = arguments[_i];
  19828. }
  19829. var result = oldPush.apply(array, items);
  19830. _this._resyncMeshes();
  19831. return result;
  19832. };
  19833. var oldSplice = array.splice;
  19834. array.splice = function (index, deleteCount) {
  19835. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19836. _this._resyncMeshes();
  19837. return deleted;
  19838. };
  19839. this._resyncMeshes();
  19840. };
  19841. Light.prototype._resyncMeshes = function () {
  19842. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19843. var mesh = _a[_i];
  19844. mesh._resyncLighSource(this);
  19845. }
  19846. };
  19847. /**
  19848. * Forces the meshes to update their light related information in their rendering used effects
  19849. * @ignore Internal Use Only
  19850. */
  19851. Light.prototype._markMeshesAsLightDirty = function () {
  19852. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19853. var mesh = _a[_i];
  19854. if (mesh._lightSources.indexOf(this) !== -1) {
  19855. mesh._markSubMeshesAsLightDirty();
  19856. }
  19857. }
  19858. };
  19859. /**
  19860. * Recomputes the cached photometric scale if needed.
  19861. */
  19862. Light.prototype._computePhotometricScale = function () {
  19863. this._photometricScale = this._getPhotometricScale();
  19864. this.getScene().resetCachedMaterial();
  19865. };
  19866. /**
  19867. * Returns the Photometric Scale according to the light type and intensity mode.
  19868. */
  19869. Light.prototype._getPhotometricScale = function () {
  19870. var photometricScale = 0.0;
  19871. var lightTypeID = this.getTypeID();
  19872. //get photometric mode
  19873. var photometricMode = this.intensityMode;
  19874. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19875. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19876. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19877. }
  19878. else {
  19879. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19880. }
  19881. }
  19882. //compute photometric scale
  19883. switch (lightTypeID) {
  19884. case Light.LIGHTTYPEID_POINTLIGHT:
  19885. case Light.LIGHTTYPEID_SPOTLIGHT:
  19886. switch (photometricMode) {
  19887. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19888. photometricScale = 1.0 / (4.0 * Math.PI);
  19889. break;
  19890. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19891. photometricScale = 1.0;
  19892. break;
  19893. case Light.INTENSITYMODE_LUMINANCE:
  19894. photometricScale = this.radius * this.radius;
  19895. break;
  19896. }
  19897. break;
  19898. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19899. switch (photometricMode) {
  19900. case Light.INTENSITYMODE_ILLUMINANCE:
  19901. photometricScale = 1.0;
  19902. break;
  19903. case Light.INTENSITYMODE_LUMINANCE:
  19904. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19905. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19906. var apexAngleRadians = this.radius;
  19907. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19908. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19909. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19910. photometricScale = solidAngle;
  19911. break;
  19912. }
  19913. break;
  19914. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19915. // No fall off in hemisperic light.
  19916. photometricScale = 1.0;
  19917. break;
  19918. }
  19919. return photometricScale;
  19920. };
  19921. /**
  19922. * Reorder the light in the scene according to their defined priority.
  19923. * @ignore Internal Use Only
  19924. */
  19925. Light.prototype._reorderLightsInScene = function () {
  19926. var scene = this.getScene();
  19927. if (this._renderPriority != 0) {
  19928. scene.requireLightSorting = true;
  19929. }
  19930. this.getScene().sortLightsByPriority();
  19931. };
  19932. //lightmapMode Consts
  19933. Light._LIGHTMAP_DEFAULT = 0;
  19934. Light._LIGHTMAP_SPECULAR = 1;
  19935. Light._LIGHTMAP_SHADOWSONLY = 2;
  19936. // Intensity Mode Consts
  19937. Light._INTENSITYMODE_AUTOMATIC = 0;
  19938. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19939. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19940. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19941. Light._INTENSITYMODE_LUMINANCE = 4;
  19942. // Light types ids const.
  19943. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19944. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19945. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19946. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19947. __decorate([
  19948. BABYLON.serializeAsColor3()
  19949. ], Light.prototype, "diffuse", void 0);
  19950. __decorate([
  19951. BABYLON.serializeAsColor3()
  19952. ], Light.prototype, "specular", void 0);
  19953. __decorate([
  19954. BABYLON.serialize()
  19955. ], Light.prototype, "intensity", void 0);
  19956. __decorate([
  19957. BABYLON.serialize()
  19958. ], Light.prototype, "range", void 0);
  19959. __decorate([
  19960. BABYLON.serialize()
  19961. ], Light.prototype, "intensityMode", null);
  19962. __decorate([
  19963. BABYLON.serialize()
  19964. ], Light.prototype, "radius", null);
  19965. __decorate([
  19966. BABYLON.serialize()
  19967. ], Light.prototype, "_renderPriority", void 0);
  19968. __decorate([
  19969. BABYLON.expandToProperty("_reorderLightsInScene")
  19970. ], Light.prototype, "renderPriority", void 0);
  19971. __decorate([
  19972. BABYLON.serialize()
  19973. ], Light.prototype, "shadowEnabled", void 0);
  19974. __decorate([
  19975. BABYLON.serialize("excludeWithLayerMask")
  19976. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19977. __decorate([
  19978. BABYLON.serialize("includeOnlyWithLayerMask")
  19979. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19980. __decorate([
  19981. BABYLON.serialize("lightmapMode")
  19982. ], Light.prototype, "_lightmapMode", void 0);
  19983. return Light;
  19984. }(BABYLON.Node));
  19985. BABYLON.Light = Light;
  19986. })(BABYLON || (BABYLON = {}));
  19987. //# sourceMappingURL=babylon.light.js.map
  19988. "use strict";
  19989. var BABYLON;
  19990. (function (BABYLON) {
  19991. var Camera = /** @class */ (function (_super) {
  19992. __extends(Camera, _super);
  19993. function Camera(name, position, scene) {
  19994. var _this = _super.call(this, name, scene) || this;
  19995. /**
  19996. * The vector the camera should consider as up.
  19997. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19998. */
  19999. _this.upVector = BABYLON.Vector3.Up();
  20000. _this.orthoLeft = null;
  20001. _this.orthoRight = null;
  20002. _this.orthoBottom = null;
  20003. _this.orthoTop = null;
  20004. /**
  20005. * FOV is set in Radians. (default is 0.8)
  20006. */
  20007. _this.fov = 0.8;
  20008. _this.minZ = 1;
  20009. _this.maxZ = 10000.0;
  20010. _this.inertia = 0.9;
  20011. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20012. _this.isIntermediate = false;
  20013. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20014. /**
  20015. * Restricts the camera to viewing objects with the same layerMask.
  20016. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20017. */
  20018. _this.layerMask = 0x0FFFFFFF;
  20019. /**
  20020. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20021. */
  20022. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20023. // Camera rig members
  20024. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20025. _this._rigCameras = new Array();
  20026. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20027. _this._skipRendering = false;
  20028. _this.customRenderTargets = new Array();
  20029. // Observables
  20030. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20031. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20032. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20033. _this.onRestoreStateObservable = new BABYLON.Observable();
  20034. // Cache
  20035. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20036. _this._projectionMatrix = new BABYLON.Matrix();
  20037. _this._doNotComputeProjectionMatrix = false;
  20038. _this._postProcesses = new Array();
  20039. _this._transformMatrix = BABYLON.Matrix.Zero();
  20040. _this._activeMeshes = new BABYLON.SmartArray(256);
  20041. _this._globalPosition = BABYLON.Vector3.Zero();
  20042. _this._refreshFrustumPlanes = true;
  20043. _this.getScene().addCamera(_this);
  20044. if (!_this.getScene().activeCamera) {
  20045. _this.getScene().activeCamera = _this;
  20046. }
  20047. _this.position = position;
  20048. return _this;
  20049. }
  20050. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20051. get: function () {
  20052. return Camera._PERSPECTIVE_CAMERA;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20058. get: function () {
  20059. return Camera._ORTHOGRAPHIC_CAMERA;
  20060. },
  20061. enumerable: true,
  20062. configurable: true
  20063. });
  20064. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20065. /**
  20066. * This is the default FOV mode for perspective cameras.
  20067. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20068. *
  20069. */
  20070. get: function () {
  20071. return Camera._FOVMODE_VERTICAL_FIXED;
  20072. },
  20073. enumerable: true,
  20074. configurable: true
  20075. });
  20076. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20077. /**
  20078. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20079. *
  20080. */
  20081. get: function () {
  20082. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20088. get: function () {
  20089. return Camera._RIG_MODE_NONE;
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20095. get: function () {
  20096. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20097. },
  20098. enumerable: true,
  20099. configurable: true
  20100. });
  20101. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20102. get: function () {
  20103. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20104. },
  20105. enumerable: true,
  20106. configurable: true
  20107. });
  20108. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20109. get: function () {
  20110. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20111. },
  20112. enumerable: true,
  20113. configurable: true
  20114. });
  20115. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20116. get: function () {
  20117. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20118. },
  20119. enumerable: true,
  20120. configurable: true
  20121. });
  20122. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20123. get: function () {
  20124. return Camera._RIG_MODE_VR;
  20125. },
  20126. enumerable: true,
  20127. configurable: true
  20128. });
  20129. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20130. get: function () {
  20131. return Camera._RIG_MODE_WEBVR;
  20132. },
  20133. enumerable: true,
  20134. configurable: true
  20135. });
  20136. /**
  20137. * Store current camera state (fov, position, etc..)
  20138. */
  20139. Camera.prototype.storeState = function () {
  20140. this._stateStored = true;
  20141. this._storedFov = this.fov;
  20142. return this;
  20143. };
  20144. /**
  20145. * Restores the camera state values if it has been stored. You must call storeState() first
  20146. */
  20147. Camera.prototype._restoreStateValues = function () {
  20148. if (!this._stateStored) {
  20149. return false;
  20150. }
  20151. this.fov = this._storedFov;
  20152. return true;
  20153. };
  20154. /**
  20155. * Restored camera state. You must call storeState() first
  20156. */
  20157. Camera.prototype.restoreState = function () {
  20158. if (this._restoreStateValues()) {
  20159. this.onRestoreStateObservable.notifyObservers(this);
  20160. return true;
  20161. }
  20162. return false;
  20163. };
  20164. Camera.prototype.getClassName = function () {
  20165. return "Camera";
  20166. };
  20167. /**
  20168. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20169. */
  20170. Camera.prototype.toString = function (fullDetails) {
  20171. var ret = "Name: " + this.name;
  20172. ret += ", type: " + this.getClassName();
  20173. if (this.animations) {
  20174. for (var i = 0; i < this.animations.length; i++) {
  20175. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20176. }
  20177. }
  20178. if (fullDetails) {
  20179. }
  20180. return ret;
  20181. };
  20182. Object.defineProperty(Camera.prototype, "globalPosition", {
  20183. get: function () {
  20184. return this._globalPosition;
  20185. },
  20186. enumerable: true,
  20187. configurable: true
  20188. });
  20189. Camera.prototype.getActiveMeshes = function () {
  20190. return this._activeMeshes;
  20191. };
  20192. Camera.prototype.isActiveMesh = function (mesh) {
  20193. return (this._activeMeshes.indexOf(mesh) !== -1);
  20194. };
  20195. /**
  20196. * Is this camera ready to be used/rendered
  20197. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  20198. * @return true if the camera is ready
  20199. */
  20200. Camera.prototype.isReady = function (completeCheck) {
  20201. if (completeCheck === void 0) { completeCheck = false; }
  20202. if (completeCheck) {
  20203. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  20204. var pp = _a[_i];
  20205. if (pp && !pp.isReady()) {
  20206. return false;
  20207. }
  20208. }
  20209. }
  20210. return _super.prototype.isReady.call(this, completeCheck);
  20211. };
  20212. //Cache
  20213. Camera.prototype._initCache = function () {
  20214. _super.prototype._initCache.call(this);
  20215. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20216. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20217. this._cache.mode = undefined;
  20218. this._cache.minZ = undefined;
  20219. this._cache.maxZ = undefined;
  20220. this._cache.fov = undefined;
  20221. this._cache.fovMode = undefined;
  20222. this._cache.aspectRatio = undefined;
  20223. this._cache.orthoLeft = undefined;
  20224. this._cache.orthoRight = undefined;
  20225. this._cache.orthoBottom = undefined;
  20226. this._cache.orthoTop = undefined;
  20227. this._cache.renderWidth = undefined;
  20228. this._cache.renderHeight = undefined;
  20229. };
  20230. Camera.prototype._updateCache = function (ignoreParentClass) {
  20231. if (!ignoreParentClass) {
  20232. _super.prototype._updateCache.call(this);
  20233. }
  20234. this._cache.position.copyFrom(this.position);
  20235. this._cache.upVector.copyFrom(this.upVector);
  20236. };
  20237. // Synchronized
  20238. Camera.prototype._isSynchronized = function () {
  20239. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20240. };
  20241. Camera.prototype._isSynchronizedViewMatrix = function () {
  20242. if (!_super.prototype._isSynchronized.call(this))
  20243. return false;
  20244. return this._cache.position.equals(this.position)
  20245. && this._cache.upVector.equals(this.upVector)
  20246. && this.isSynchronizedWithParent();
  20247. };
  20248. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20249. var check = this._cache.mode === this.mode
  20250. && this._cache.minZ === this.minZ
  20251. && this._cache.maxZ === this.maxZ;
  20252. if (!check) {
  20253. return false;
  20254. }
  20255. var engine = this.getEngine();
  20256. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20257. check = this._cache.fov === this.fov
  20258. && this._cache.fovMode === this.fovMode
  20259. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20260. }
  20261. else {
  20262. check = this._cache.orthoLeft === this.orthoLeft
  20263. && this._cache.orthoRight === this.orthoRight
  20264. && this._cache.orthoBottom === this.orthoBottom
  20265. && this._cache.orthoTop === this.orthoTop
  20266. && this._cache.renderWidth === engine.getRenderWidth()
  20267. && this._cache.renderHeight === engine.getRenderHeight();
  20268. }
  20269. return check;
  20270. };
  20271. // Controls
  20272. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20273. };
  20274. Camera.prototype.detachControl = function (element) {
  20275. };
  20276. Camera.prototype.update = function () {
  20277. this._checkInputs();
  20278. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20279. this._updateRigCameras();
  20280. }
  20281. };
  20282. Camera.prototype._checkInputs = function () {
  20283. this.onAfterCheckInputsObservable.notifyObservers(this);
  20284. };
  20285. Object.defineProperty(Camera.prototype, "rigCameras", {
  20286. get: function () {
  20287. return this._rigCameras;
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20293. get: function () {
  20294. return this._rigPostProcess;
  20295. },
  20296. enumerable: true,
  20297. configurable: true
  20298. });
  20299. /**
  20300. * Internal, gets the first post proces.
  20301. * @returns the first post process to be run on this camera.
  20302. */
  20303. Camera.prototype._getFirstPostProcess = function () {
  20304. for (var pp in this._postProcesses) {
  20305. if (this._postProcesses[pp] !== null) {
  20306. return this._postProcesses[pp];
  20307. }
  20308. }
  20309. return null;
  20310. };
  20311. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20312. // invalidate framebuffer
  20313. var firstPostProcess = this._getFirstPostProcess();
  20314. if (firstPostProcess) {
  20315. firstPostProcess.markTextureDirty();
  20316. }
  20317. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20318. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20319. var cam = this._rigCameras[i];
  20320. var rigPostProcess = cam._rigPostProcess;
  20321. // for VR rig, there does not have to be a post process
  20322. if (rigPostProcess) {
  20323. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20324. if (isPass) {
  20325. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20326. cam.isIntermediate = this._postProcesses.length === 0;
  20327. }
  20328. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20329. rigPostProcess.markTextureDirty();
  20330. }
  20331. else {
  20332. cam._postProcesses = this._postProcesses.slice(0);
  20333. }
  20334. }
  20335. };
  20336. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20337. if (insertAt === void 0) { insertAt = null; }
  20338. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20339. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20340. return 0;
  20341. }
  20342. if (insertAt == null || insertAt < 0) {
  20343. this._postProcesses.push(postProcess);
  20344. }
  20345. else if (this._postProcesses[insertAt] === null) {
  20346. this._postProcesses[insertAt] = postProcess;
  20347. }
  20348. else {
  20349. this._postProcesses.splice(insertAt, 0, postProcess);
  20350. }
  20351. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20352. return this._postProcesses.indexOf(postProcess);
  20353. };
  20354. Camera.prototype.detachPostProcess = function (postProcess) {
  20355. var idx = this._postProcesses.indexOf(postProcess);
  20356. if (idx !== -1) {
  20357. this._postProcesses[idx] = null;
  20358. }
  20359. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20360. };
  20361. Camera.prototype.getWorldMatrix = function () {
  20362. if (!this._worldMatrix) {
  20363. this._worldMatrix = BABYLON.Matrix.Identity();
  20364. }
  20365. var viewMatrix = this.getViewMatrix();
  20366. viewMatrix.invertToRef(this._worldMatrix);
  20367. return this._worldMatrix;
  20368. };
  20369. Camera.prototype._getViewMatrix = function () {
  20370. return BABYLON.Matrix.Identity();
  20371. };
  20372. Camera.prototype.getViewMatrix = function (force) {
  20373. if (!force && this._isSynchronizedViewMatrix()) {
  20374. return this._computedViewMatrix;
  20375. }
  20376. this.updateCache();
  20377. this._computedViewMatrix = this._getViewMatrix();
  20378. this._currentRenderId = this.getScene().getRenderId();
  20379. this._refreshFrustumPlanes = true;
  20380. if (!this.parent || !this.parent.getWorldMatrix) {
  20381. this._globalPosition.copyFrom(this.position);
  20382. }
  20383. else {
  20384. if (!this._worldMatrix) {
  20385. this._worldMatrix = BABYLON.Matrix.Identity();
  20386. }
  20387. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20388. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20389. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20390. this._computedViewMatrix.invert();
  20391. this._markSyncedWithParent();
  20392. }
  20393. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20394. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20395. }
  20396. this.onViewMatrixChangedObservable.notifyObservers(this);
  20397. return this._computedViewMatrix;
  20398. };
  20399. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20400. this._doNotComputeProjectionMatrix = true;
  20401. if (projection !== undefined) {
  20402. this._projectionMatrix = projection;
  20403. }
  20404. };
  20405. ;
  20406. Camera.prototype.unfreezeProjectionMatrix = function () {
  20407. this._doNotComputeProjectionMatrix = false;
  20408. };
  20409. ;
  20410. Camera.prototype.getProjectionMatrix = function (force) {
  20411. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20412. return this._projectionMatrix;
  20413. }
  20414. // Cache
  20415. this._cache.mode = this.mode;
  20416. this._cache.minZ = this.minZ;
  20417. this._cache.maxZ = this.maxZ;
  20418. // Matrix
  20419. this._refreshFrustumPlanes = true;
  20420. var engine = this.getEngine();
  20421. var scene = this.getScene();
  20422. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20423. this._cache.fov = this.fov;
  20424. this._cache.fovMode = this.fovMode;
  20425. this._cache.aspectRatio = engine.getAspectRatio(this);
  20426. if (this.minZ <= 0) {
  20427. this.minZ = 0.1;
  20428. }
  20429. if (scene.useRightHandedSystem) {
  20430. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20431. }
  20432. else {
  20433. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20434. }
  20435. }
  20436. else {
  20437. var halfWidth = engine.getRenderWidth() / 2.0;
  20438. var halfHeight = engine.getRenderHeight() / 2.0;
  20439. if (scene.useRightHandedSystem) {
  20440. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20441. }
  20442. else {
  20443. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20444. }
  20445. this._cache.orthoLeft = this.orthoLeft;
  20446. this._cache.orthoRight = this.orthoRight;
  20447. this._cache.orthoBottom = this.orthoBottom;
  20448. this._cache.orthoTop = this.orthoTop;
  20449. this._cache.renderWidth = engine.getRenderWidth();
  20450. this._cache.renderHeight = engine.getRenderHeight();
  20451. }
  20452. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20453. return this._projectionMatrix;
  20454. };
  20455. Camera.prototype.getTranformationMatrix = function () {
  20456. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20457. return this._transformMatrix;
  20458. };
  20459. Camera.prototype.updateFrustumPlanes = function () {
  20460. if (!this._refreshFrustumPlanes) {
  20461. return;
  20462. }
  20463. this.getTranformationMatrix();
  20464. if (!this._frustumPlanes) {
  20465. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20466. }
  20467. else {
  20468. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20469. }
  20470. this._refreshFrustumPlanes = false;
  20471. };
  20472. Camera.prototype.isInFrustum = function (target) {
  20473. this.updateFrustumPlanes();
  20474. return target.isInFrustum(this._frustumPlanes);
  20475. };
  20476. Camera.prototype.isCompletelyInFrustum = function (target) {
  20477. this.updateFrustumPlanes();
  20478. return target.isCompletelyInFrustum(this._frustumPlanes);
  20479. };
  20480. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20481. if (length === void 0) { length = 100; }
  20482. if (!transform) {
  20483. transform = this.getWorldMatrix();
  20484. }
  20485. if (!origin) {
  20486. origin = this.position;
  20487. }
  20488. var forward = new BABYLON.Vector3(0, 0, 1);
  20489. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20490. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20491. return new BABYLON.Ray(origin, direction, length);
  20492. };
  20493. /**
  20494. * Releases resources associated with this node.
  20495. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20496. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20497. */
  20498. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20499. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20500. // Observables
  20501. this.onViewMatrixChangedObservable.clear();
  20502. this.onProjectionMatrixChangedObservable.clear();
  20503. this.onAfterCheckInputsObservable.clear();
  20504. this.onRestoreStateObservable.clear();
  20505. // Inputs
  20506. if (this.inputs) {
  20507. this.inputs.clear();
  20508. }
  20509. // Animations
  20510. this.getScene().stopAnimation(this);
  20511. // Remove from scene
  20512. this.getScene().removeCamera(this);
  20513. while (this._rigCameras.length > 0) {
  20514. var camera = this._rigCameras.pop();
  20515. if (camera) {
  20516. camera.dispose();
  20517. }
  20518. }
  20519. // Postprocesses
  20520. if (this._rigPostProcess) {
  20521. this._rigPostProcess.dispose(this);
  20522. this._rigPostProcess = null;
  20523. this._postProcesses = [];
  20524. }
  20525. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20526. this._rigPostProcess = null;
  20527. this._postProcesses = [];
  20528. }
  20529. else {
  20530. var i = this._postProcesses.length;
  20531. while (--i >= 0) {
  20532. var postProcess = this._postProcesses[i];
  20533. if (postProcess) {
  20534. postProcess.dispose(this);
  20535. }
  20536. }
  20537. }
  20538. // Render targets
  20539. var i = this.customRenderTargets.length;
  20540. while (--i >= 0) {
  20541. this.customRenderTargets[i].dispose();
  20542. }
  20543. this.customRenderTargets = [];
  20544. // Active Meshes
  20545. this._activeMeshes.dispose();
  20546. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20547. };
  20548. Object.defineProperty(Camera.prototype, "leftCamera", {
  20549. // ---- Camera rigs section ----
  20550. get: function () {
  20551. if (this._rigCameras.length < 1) {
  20552. return null;
  20553. }
  20554. return this._rigCameras[0];
  20555. },
  20556. enumerable: true,
  20557. configurable: true
  20558. });
  20559. Object.defineProperty(Camera.prototype, "rightCamera", {
  20560. get: function () {
  20561. if (this._rigCameras.length < 2) {
  20562. return null;
  20563. }
  20564. return this._rigCameras[1];
  20565. },
  20566. enumerable: true,
  20567. configurable: true
  20568. });
  20569. Camera.prototype.getLeftTarget = function () {
  20570. if (this._rigCameras.length < 1) {
  20571. return null;
  20572. }
  20573. return this._rigCameras[0].getTarget();
  20574. };
  20575. Camera.prototype.getRightTarget = function () {
  20576. if (this._rigCameras.length < 2) {
  20577. return null;
  20578. }
  20579. return this._rigCameras[1].getTarget();
  20580. };
  20581. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20582. if (this.cameraRigMode === mode) {
  20583. return;
  20584. }
  20585. while (this._rigCameras.length > 0) {
  20586. var camera = this._rigCameras.pop();
  20587. if (camera) {
  20588. camera.dispose();
  20589. }
  20590. }
  20591. this.cameraRigMode = mode;
  20592. this._cameraRigParams = {};
  20593. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20594. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20595. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20596. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20597. // create the rig cameras, unless none
  20598. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20599. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20600. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20601. if (leftCamera && rightCamera) {
  20602. this._rigCameras.push(leftCamera);
  20603. this._rigCameras.push(rightCamera);
  20604. }
  20605. }
  20606. switch (this.cameraRigMode) {
  20607. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20608. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20609. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20610. break;
  20611. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20612. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20613. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20614. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20615. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20616. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20617. break;
  20618. case Camera.RIG_MODE_VR:
  20619. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20620. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20621. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20622. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20623. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20624. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20625. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20626. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20627. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20628. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20629. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20630. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20631. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20632. if (metrics.compensateDistortion) {
  20633. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20634. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20635. }
  20636. break;
  20637. case Camera.RIG_MODE_WEBVR:
  20638. if (rigParams.vrDisplay) {
  20639. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20640. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20641. //Left eye
  20642. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20643. this._rigCameras[0].setCameraRigParameter("left", true);
  20644. //leaving this for future reference
  20645. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20646. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20647. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20648. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20649. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20650. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20651. this._rigCameras[0].parent = this;
  20652. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20653. //Right eye
  20654. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20655. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20656. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20657. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20658. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20659. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20660. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20661. this._rigCameras[1].parent = this;
  20662. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20663. if (Camera.UseAlternateWebVRRendering) {
  20664. this._rigCameras[1]._skipRendering = true;
  20665. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20666. }
  20667. }
  20668. break;
  20669. }
  20670. this._cascadePostProcessesToRigCams();
  20671. this.update();
  20672. };
  20673. Camera.prototype._getVRProjectionMatrix = function () {
  20674. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20675. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20676. return this._projectionMatrix;
  20677. };
  20678. Camera.prototype._updateCameraRotationMatrix = function () {
  20679. //Here for WebVR
  20680. };
  20681. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20682. //Here for WebVR
  20683. };
  20684. /**
  20685. * This function MUST be overwritten by the different WebVR cameras available.
  20686. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20687. */
  20688. Camera.prototype._getWebVRProjectionMatrix = function () {
  20689. return BABYLON.Matrix.Identity();
  20690. };
  20691. /**
  20692. * This function MUST be overwritten by the different WebVR cameras available.
  20693. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20694. */
  20695. Camera.prototype._getWebVRViewMatrix = function () {
  20696. return BABYLON.Matrix.Identity();
  20697. };
  20698. Camera.prototype.setCameraRigParameter = function (name, value) {
  20699. if (!this._cameraRigParams) {
  20700. this._cameraRigParams = {};
  20701. }
  20702. this._cameraRigParams[name] = value;
  20703. //provisionnally:
  20704. if (name === "interaxialDistance") {
  20705. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20706. }
  20707. };
  20708. /**
  20709. * needs to be overridden by children so sub has required properties to be copied
  20710. */
  20711. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20712. return null;
  20713. };
  20714. /**
  20715. * May need to be overridden by children
  20716. */
  20717. Camera.prototype._updateRigCameras = function () {
  20718. for (var i = 0; i < this._rigCameras.length; i++) {
  20719. this._rigCameras[i].minZ = this.minZ;
  20720. this._rigCameras[i].maxZ = this.maxZ;
  20721. this._rigCameras[i].fov = this.fov;
  20722. }
  20723. // only update viewport when ANAGLYPH
  20724. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20725. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20726. }
  20727. };
  20728. Camera.prototype._setupInputs = function () {
  20729. };
  20730. Camera.prototype.serialize = function () {
  20731. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20732. // Type
  20733. serializationObject.type = this.getClassName();
  20734. // Parent
  20735. if (this.parent) {
  20736. serializationObject.parentId = this.parent.id;
  20737. }
  20738. if (this.inputs) {
  20739. this.inputs.serialize(serializationObject);
  20740. }
  20741. // Animations
  20742. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20743. serializationObject.ranges = this.serializeAnimationRanges();
  20744. return serializationObject;
  20745. };
  20746. Camera.prototype.clone = function (name) {
  20747. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20748. };
  20749. Camera.prototype.getDirection = function (localAxis) {
  20750. var result = BABYLON.Vector3.Zero();
  20751. this.getDirectionToRef(localAxis, result);
  20752. return result;
  20753. };
  20754. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20755. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20756. };
  20757. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20758. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20759. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20760. switch (type) {
  20761. case "ArcRotateCamera":
  20762. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20763. case "DeviceOrientationCamera":
  20764. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20765. case "FollowCamera":
  20766. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20767. case "ArcFollowCamera":
  20768. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20769. case "GamepadCamera":
  20770. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20771. case "TouchCamera":
  20772. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20773. case "VirtualJoysticksCamera":
  20774. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20775. case "WebVRFreeCamera":
  20776. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20777. case "WebVRGamepadCamera":
  20778. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20779. case "VRDeviceOrientationFreeCamera":
  20780. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20781. case "VRDeviceOrientationGamepadCamera":
  20782. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20783. case "AnaglyphArcRotateCamera":
  20784. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20785. case "AnaglyphFreeCamera":
  20786. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20787. case "AnaglyphGamepadCamera":
  20788. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20789. case "AnaglyphUniversalCamera":
  20790. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20791. case "StereoscopicArcRotateCamera":
  20792. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20793. case "StereoscopicFreeCamera":
  20794. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20795. case "StereoscopicGamepadCamera":
  20796. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20797. case "StereoscopicUniversalCamera":
  20798. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20799. case "FreeCamera":// Forcing Universal here
  20800. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20801. default:// Universal Camera is the default value
  20802. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20803. }
  20804. };
  20805. Camera.prototype.computeWorldMatrix = function () {
  20806. return this.getWorldMatrix();
  20807. };
  20808. Camera.Parse = function (parsedCamera, scene) {
  20809. var type = parsedCamera.type;
  20810. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20811. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20812. // Parent
  20813. if (parsedCamera.parentId) {
  20814. camera._waitingParentId = parsedCamera.parentId;
  20815. }
  20816. //If camera has an input manager, let it parse inputs settings
  20817. if (camera.inputs) {
  20818. camera.inputs.parse(parsedCamera);
  20819. camera._setupInputs();
  20820. }
  20821. if (camera.setPosition) {
  20822. camera.position.copyFromFloats(0, 0, 0);
  20823. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20824. }
  20825. // Target
  20826. if (parsedCamera.target) {
  20827. if (camera.setTarget) {
  20828. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20829. }
  20830. }
  20831. // Apply 3d rig, when found
  20832. if (parsedCamera.cameraRigMode) {
  20833. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20834. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20835. }
  20836. // Animations
  20837. if (parsedCamera.animations) {
  20838. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20839. var parsedAnimation = parsedCamera.animations[animationIndex];
  20840. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20841. }
  20842. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20843. }
  20844. if (parsedCamera.autoAnimate) {
  20845. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20846. }
  20847. return camera;
  20848. };
  20849. // Statics
  20850. Camera._PERSPECTIVE_CAMERA = 0;
  20851. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20852. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20853. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20854. Camera._RIG_MODE_NONE = 0;
  20855. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20856. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20857. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20858. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20859. Camera._RIG_MODE_VR = 20;
  20860. Camera._RIG_MODE_WEBVR = 21;
  20861. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20862. Camera.UseAlternateWebVRRendering = false;
  20863. __decorate([
  20864. BABYLON.serializeAsVector3()
  20865. ], Camera.prototype, "position", void 0);
  20866. __decorate([
  20867. BABYLON.serializeAsVector3()
  20868. ], Camera.prototype, "upVector", void 0);
  20869. __decorate([
  20870. BABYLON.serialize()
  20871. ], Camera.prototype, "orthoLeft", void 0);
  20872. __decorate([
  20873. BABYLON.serialize()
  20874. ], Camera.prototype, "orthoRight", void 0);
  20875. __decorate([
  20876. BABYLON.serialize()
  20877. ], Camera.prototype, "orthoBottom", void 0);
  20878. __decorate([
  20879. BABYLON.serialize()
  20880. ], Camera.prototype, "orthoTop", void 0);
  20881. __decorate([
  20882. BABYLON.serialize()
  20883. ], Camera.prototype, "fov", void 0);
  20884. __decorate([
  20885. BABYLON.serialize()
  20886. ], Camera.prototype, "minZ", void 0);
  20887. __decorate([
  20888. BABYLON.serialize()
  20889. ], Camera.prototype, "maxZ", void 0);
  20890. __decorate([
  20891. BABYLON.serialize()
  20892. ], Camera.prototype, "inertia", void 0);
  20893. __decorate([
  20894. BABYLON.serialize()
  20895. ], Camera.prototype, "mode", void 0);
  20896. __decorate([
  20897. BABYLON.serialize()
  20898. ], Camera.prototype, "layerMask", void 0);
  20899. __decorate([
  20900. BABYLON.serialize()
  20901. ], Camera.prototype, "fovMode", void 0);
  20902. __decorate([
  20903. BABYLON.serialize()
  20904. ], Camera.prototype, "cameraRigMode", void 0);
  20905. __decorate([
  20906. BABYLON.serialize()
  20907. ], Camera.prototype, "interaxialDistance", void 0);
  20908. __decorate([
  20909. BABYLON.serialize()
  20910. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20911. return Camera;
  20912. }(BABYLON.Node));
  20913. BABYLON.Camera = Camera;
  20914. })(BABYLON || (BABYLON = {}));
  20915. //# sourceMappingURL=babylon.camera.js.map
  20916. "use strict";
  20917. var BABYLON;
  20918. (function (BABYLON) {
  20919. var RenderingManager = /** @class */ (function () {
  20920. function RenderingManager(scene) {
  20921. this._renderingGroups = new Array();
  20922. this._autoClearDepthStencil = {};
  20923. this._customOpaqueSortCompareFn = {};
  20924. this._customAlphaTestSortCompareFn = {};
  20925. this._customTransparentSortCompareFn = {};
  20926. this._renderinGroupInfo = null;
  20927. this._scene = scene;
  20928. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20929. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20930. }
  20931. }
  20932. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20933. if (depth === void 0) { depth = true; }
  20934. if (stencil === void 0) { stencil = true; }
  20935. if (this._depthStencilBufferAlreadyCleaned) {
  20936. return;
  20937. }
  20938. this._scene.getEngine().clear(null, false, depth, stencil);
  20939. this._depthStencilBufferAlreadyCleaned = true;
  20940. };
  20941. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20942. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20943. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20944. var info = null;
  20945. if (observable) {
  20946. if (!this._renderinGroupInfo) {
  20947. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20948. }
  20949. info = this._renderinGroupInfo;
  20950. info.scene = this._scene;
  20951. info.camera = this._scene.activeCamera;
  20952. }
  20953. // Dispatch sprites
  20954. if (renderSprites) {
  20955. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20956. var manager = this._scene.spriteManagers[index];
  20957. this.dispatchSprites(manager);
  20958. }
  20959. }
  20960. // Render
  20961. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20962. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20963. var renderingGroup = this._renderingGroups[index];
  20964. if (!renderingGroup && !observable)
  20965. continue;
  20966. var renderingGroupMask = 0;
  20967. // Fire PRECLEAR stage
  20968. if (observable && info) {
  20969. renderingGroupMask = Math.pow(2, index);
  20970. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20971. info.renderingGroupId = index;
  20972. observable.notifyObservers(info, renderingGroupMask);
  20973. }
  20974. // Clear depth/stencil if needed
  20975. if (RenderingManager.AUTOCLEAR) {
  20976. var autoClear = this._autoClearDepthStencil[index];
  20977. if (autoClear && autoClear.autoClear) {
  20978. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20979. }
  20980. }
  20981. if (observable && info) {
  20982. // Fire PREOPAQUE stage
  20983. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20984. observable.notifyObservers(info, renderingGroupMask);
  20985. // Fire PRETRANSPARENT stage
  20986. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20987. observable.notifyObservers(info, renderingGroupMask);
  20988. }
  20989. if (renderingGroup)
  20990. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20991. // Fire POSTTRANSPARENT stage
  20992. if (observable && info) {
  20993. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20994. observable.notifyObservers(info, renderingGroupMask);
  20995. }
  20996. }
  20997. };
  20998. RenderingManager.prototype.reset = function () {
  20999. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21000. var renderingGroup = this._renderingGroups[index];
  21001. if (renderingGroup) {
  21002. renderingGroup.prepare();
  21003. }
  21004. }
  21005. };
  21006. RenderingManager.prototype.dispose = function () {
  21007. this.freeRenderingGroups();
  21008. this._renderingGroups.length = 0;
  21009. };
  21010. /**
  21011. * Clear the info related to rendering groups preventing retention points during dispose.
  21012. */
  21013. RenderingManager.prototype.freeRenderingGroups = function () {
  21014. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21015. var renderingGroup = this._renderingGroups[index];
  21016. if (renderingGroup) {
  21017. renderingGroup.dispose();
  21018. }
  21019. }
  21020. };
  21021. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21022. if (this._renderingGroups[renderingGroupId] === undefined) {
  21023. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21024. }
  21025. };
  21026. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21027. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21028. this._prepareRenderingGroup(renderingGroupId);
  21029. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21030. };
  21031. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21032. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21033. this._prepareRenderingGroup(renderingGroupId);
  21034. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21035. };
  21036. /**
  21037. * @param subMesh The submesh to dispatch
  21038. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21039. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21040. */
  21041. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21042. if (mesh === undefined) {
  21043. mesh = subMesh.getMesh();
  21044. }
  21045. var renderingGroupId = mesh.renderingGroupId || 0;
  21046. this._prepareRenderingGroup(renderingGroupId);
  21047. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21048. };
  21049. /**
  21050. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21051. * This allowed control for front to back rendering or reversly depending of the special needs.
  21052. *
  21053. * @param renderingGroupId The rendering group id corresponding to its index
  21054. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21055. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21056. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21057. */
  21058. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21059. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21060. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21061. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21062. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21063. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21064. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21065. if (this._renderingGroups[renderingGroupId]) {
  21066. var group = this._renderingGroups[renderingGroupId];
  21067. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21068. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21069. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21070. }
  21071. };
  21072. /**
  21073. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21074. *
  21075. * @param renderingGroupId The rendering group id corresponding to its index
  21076. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21077. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21078. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21079. */
  21080. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21081. if (depth === void 0) { depth = true; }
  21082. if (stencil === void 0) { stencil = true; }
  21083. this._autoClearDepthStencil[renderingGroupId] = {
  21084. autoClear: autoClearDepthStencil,
  21085. depth: depth,
  21086. stencil: stencil
  21087. };
  21088. };
  21089. /**
  21090. * The max id used for rendering groups (not included)
  21091. */
  21092. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21093. /**
  21094. * The min id used for rendering groups (included)
  21095. */
  21096. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21097. /**
  21098. * Used to globally prevent autoclearing scenes.
  21099. */
  21100. RenderingManager.AUTOCLEAR = true;
  21101. return RenderingManager;
  21102. }());
  21103. BABYLON.RenderingManager = RenderingManager;
  21104. })(BABYLON || (BABYLON = {}));
  21105. //# sourceMappingURL=babylon.renderingManager.js.map
  21106. "use strict";
  21107. var BABYLON;
  21108. (function (BABYLON) {
  21109. var RenderingGroup = /** @class */ (function () {
  21110. /**
  21111. * Creates a new rendering group.
  21112. * @param index The rendering group index
  21113. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21114. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21115. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21116. */
  21117. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21118. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21119. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21120. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21121. this.index = index;
  21122. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21123. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21124. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21125. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21126. this._particleSystems = new BABYLON.SmartArray(256);
  21127. this._spriteManagers = new BABYLON.SmartArray(256);
  21128. this._edgesRenderers = new BABYLON.SmartArray(16);
  21129. this._scene = scene;
  21130. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21131. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21132. this.transparentSortCompareFn = transparentSortCompareFn;
  21133. }
  21134. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21135. /**
  21136. * Set the opaque sort comparison function.
  21137. * If null the sub meshes will be render in the order they were created
  21138. */
  21139. set: function (value) {
  21140. this._opaqueSortCompareFn = value;
  21141. if (value) {
  21142. this._renderOpaque = this.renderOpaqueSorted;
  21143. }
  21144. else {
  21145. this._renderOpaque = RenderingGroup.renderUnsorted;
  21146. }
  21147. },
  21148. enumerable: true,
  21149. configurable: true
  21150. });
  21151. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21152. /**
  21153. * Set the alpha test sort comparison function.
  21154. * If null the sub meshes will be render in the order they were created
  21155. */
  21156. set: function (value) {
  21157. this._alphaTestSortCompareFn = value;
  21158. if (value) {
  21159. this._renderAlphaTest = this.renderAlphaTestSorted;
  21160. }
  21161. else {
  21162. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21163. }
  21164. },
  21165. enumerable: true,
  21166. configurable: true
  21167. });
  21168. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21169. /**
  21170. * Set the transparent sort comparison function.
  21171. * If null the sub meshes will be render in the order they were created
  21172. */
  21173. set: function (value) {
  21174. if (value) {
  21175. this._transparentSortCompareFn = value;
  21176. }
  21177. else {
  21178. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21179. }
  21180. this._renderTransparent = this.renderTransparentSorted;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. /**
  21186. * Render all the sub meshes contained in the group.
  21187. * @param customRenderFunction Used to override the default render behaviour of the group.
  21188. * @returns true if rendered some submeshes.
  21189. */
  21190. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21191. if (customRenderFunction) {
  21192. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21193. return;
  21194. }
  21195. var engine = this._scene.getEngine();
  21196. // Depth only
  21197. if (this._depthOnlySubMeshes.length !== 0) {
  21198. engine.setColorWrite(false);
  21199. this._renderAlphaTest(this._depthOnlySubMeshes);
  21200. engine.setColorWrite(true);
  21201. }
  21202. // Opaque
  21203. if (this._opaqueSubMeshes.length !== 0) {
  21204. this._renderOpaque(this._opaqueSubMeshes);
  21205. }
  21206. // Alpha test
  21207. if (this._alphaTestSubMeshes.length !== 0) {
  21208. this._renderAlphaTest(this._alphaTestSubMeshes);
  21209. }
  21210. var stencilState = engine.getStencilBuffer();
  21211. engine.setStencilBuffer(false);
  21212. // Sprites
  21213. if (renderSprites) {
  21214. this._renderSprites();
  21215. }
  21216. // Particles
  21217. if (renderParticles) {
  21218. this._renderParticles(activeMeshes);
  21219. }
  21220. if (this.onBeforeTransparentRendering) {
  21221. this.onBeforeTransparentRendering();
  21222. }
  21223. // Transparent
  21224. if (this._transparentSubMeshes.length !== 0) {
  21225. this._renderTransparent(this._transparentSubMeshes);
  21226. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21227. }
  21228. // Set back stencil to false in case it changes before the edge renderer.
  21229. engine.setStencilBuffer(false);
  21230. // Edges
  21231. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21232. this._edgesRenderers.data[edgesRendererIndex].render();
  21233. }
  21234. // Restore Stencil state.
  21235. engine.setStencilBuffer(stencilState);
  21236. };
  21237. /**
  21238. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21239. * @param subMeshes The submeshes to render
  21240. */
  21241. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21242. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21243. };
  21244. /**
  21245. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21246. * @param subMeshes The submeshes to render
  21247. */
  21248. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21249. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21250. };
  21251. /**
  21252. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21253. * @param subMeshes The submeshes to render
  21254. */
  21255. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21256. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21257. };
  21258. /**
  21259. * Renders the submeshes in a specified order.
  21260. * @param subMeshes The submeshes to sort before render
  21261. * @param sortCompareFn The comparison function use to sort
  21262. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21263. * @param transparent Specifies to activate blending if true
  21264. */
  21265. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21266. var subIndex = 0;
  21267. var subMesh;
  21268. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21269. for (; subIndex < subMeshes.length; subIndex++) {
  21270. subMesh = subMeshes.data[subIndex];
  21271. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21272. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21273. }
  21274. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21275. if (sortCompareFn) {
  21276. sortedArray.sort(sortCompareFn);
  21277. }
  21278. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21279. subMesh = sortedArray[subIndex];
  21280. if (transparent) {
  21281. var material = subMesh.getMaterial();
  21282. if (material && material.needDepthPrePass) {
  21283. var engine = material.getScene().getEngine();
  21284. engine.setColorWrite(false);
  21285. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21286. subMesh.render(false);
  21287. engine.setColorWrite(true);
  21288. }
  21289. }
  21290. subMesh.render(transparent);
  21291. }
  21292. };
  21293. /**
  21294. * Renders the submeshes in the order they were dispatched (no sort applied).
  21295. * @param subMeshes The submeshes to render
  21296. */
  21297. RenderingGroup.renderUnsorted = function (subMeshes) {
  21298. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21299. var submesh = subMeshes.data[subIndex];
  21300. submesh.render(false);
  21301. }
  21302. };
  21303. /**
  21304. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21305. * are rendered back to front if in the same alpha index.
  21306. *
  21307. * @param a The first submesh
  21308. * @param b The second submesh
  21309. * @returns The result of the comparison
  21310. */
  21311. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21312. // Alpha index first
  21313. if (a._alphaIndex > b._alphaIndex) {
  21314. return 1;
  21315. }
  21316. if (a._alphaIndex < b._alphaIndex) {
  21317. return -1;
  21318. }
  21319. // Then distance to camera
  21320. return RenderingGroup.backToFrontSortCompare(a, b);
  21321. };
  21322. /**
  21323. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21324. * are rendered back to front.
  21325. *
  21326. * @param a The first submesh
  21327. * @param b The second submesh
  21328. * @returns The result of the comparison
  21329. */
  21330. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21331. // Then distance to camera
  21332. if (a._distanceToCamera < b._distanceToCamera) {
  21333. return 1;
  21334. }
  21335. if (a._distanceToCamera > b._distanceToCamera) {
  21336. return -1;
  21337. }
  21338. return 0;
  21339. };
  21340. /**
  21341. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21342. * are rendered front to back (prevent overdraw).
  21343. *
  21344. * @param a The first submesh
  21345. * @param b The second submesh
  21346. * @returns The result of the comparison
  21347. */
  21348. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21349. // Then distance to camera
  21350. if (a._distanceToCamera < b._distanceToCamera) {
  21351. return -1;
  21352. }
  21353. if (a._distanceToCamera > b._distanceToCamera) {
  21354. return 1;
  21355. }
  21356. return 0;
  21357. };
  21358. /**
  21359. * Resets the different lists of submeshes to prepare a new frame.
  21360. */
  21361. RenderingGroup.prototype.prepare = function () {
  21362. this._opaqueSubMeshes.reset();
  21363. this._transparentSubMeshes.reset();
  21364. this._alphaTestSubMeshes.reset();
  21365. this._depthOnlySubMeshes.reset();
  21366. this._particleSystems.reset();
  21367. this._spriteManagers.reset();
  21368. this._edgesRenderers.reset();
  21369. };
  21370. RenderingGroup.prototype.dispose = function () {
  21371. this._opaqueSubMeshes.dispose();
  21372. this._transparentSubMeshes.dispose();
  21373. this._alphaTestSubMeshes.dispose();
  21374. this._depthOnlySubMeshes.dispose();
  21375. this._particleSystems.dispose();
  21376. this._spriteManagers.dispose();
  21377. this._edgesRenderers.dispose();
  21378. };
  21379. /**
  21380. * Inserts the submesh in its correct queue depending on its material.
  21381. * @param subMesh The submesh to dispatch
  21382. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21383. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21384. */
  21385. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21386. // Get mesh and materials if not provided
  21387. if (mesh === undefined) {
  21388. mesh = subMesh.getMesh();
  21389. }
  21390. if (material === undefined) {
  21391. material = subMesh.getMaterial();
  21392. }
  21393. if (material === null || material === undefined) {
  21394. return;
  21395. }
  21396. if (material.needAlphaBlendingForMesh(mesh)) {
  21397. this._transparentSubMeshes.push(subMesh);
  21398. }
  21399. else if (material.needAlphaTesting()) {
  21400. if (material.needDepthPrePass) {
  21401. this._depthOnlySubMeshes.push(subMesh);
  21402. }
  21403. this._alphaTestSubMeshes.push(subMesh);
  21404. }
  21405. else {
  21406. if (material.needDepthPrePass) {
  21407. this._depthOnlySubMeshes.push(subMesh);
  21408. }
  21409. this._opaqueSubMeshes.push(subMesh); // Opaque
  21410. }
  21411. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21412. this._edgesRenderers.push(mesh._edgesRenderer);
  21413. }
  21414. };
  21415. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21416. this._spriteManagers.push(spriteManager);
  21417. };
  21418. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21419. this._particleSystems.push(particleSystem);
  21420. };
  21421. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21422. if (this._particleSystems.length === 0) {
  21423. return;
  21424. }
  21425. // Particles
  21426. var activeCamera = this._scene.activeCamera;
  21427. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21428. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21429. var particleSystem = this._particleSystems.data[particleIndex];
  21430. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21431. continue;
  21432. }
  21433. var emitter = particleSystem.emitter;
  21434. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21435. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21436. }
  21437. }
  21438. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21439. };
  21440. RenderingGroup.prototype._renderSprites = function () {
  21441. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21442. return;
  21443. }
  21444. // Sprites
  21445. var activeCamera = this._scene.activeCamera;
  21446. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21447. for (var id = 0; id < this._spriteManagers.length; id++) {
  21448. var spriteManager = this._spriteManagers.data[id];
  21449. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21450. spriteManager.render();
  21451. }
  21452. }
  21453. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21454. };
  21455. return RenderingGroup;
  21456. }());
  21457. BABYLON.RenderingGroup = RenderingGroup;
  21458. })(BABYLON || (BABYLON = {}));
  21459. //# sourceMappingURL=babylon.renderingGroup.js.map
  21460. "use strict";
  21461. var BABYLON;
  21462. (function (BABYLON) {
  21463. var ClickInfo = /** @class */ (function () {
  21464. function ClickInfo() {
  21465. this._singleClick = false;
  21466. this._doubleClick = false;
  21467. this._hasSwiped = false;
  21468. this._ignore = false;
  21469. }
  21470. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21471. get: function () {
  21472. return this._singleClick;
  21473. },
  21474. set: function (b) {
  21475. this._singleClick = b;
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21481. get: function () {
  21482. return this._doubleClick;
  21483. },
  21484. set: function (b) {
  21485. this._doubleClick = b;
  21486. },
  21487. enumerable: true,
  21488. configurable: true
  21489. });
  21490. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21491. get: function () {
  21492. return this._hasSwiped;
  21493. },
  21494. set: function (b) {
  21495. this._hasSwiped = b;
  21496. },
  21497. enumerable: true,
  21498. configurable: true
  21499. });
  21500. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21501. get: function () {
  21502. return this._ignore;
  21503. },
  21504. set: function (b) {
  21505. this._ignore = b;
  21506. },
  21507. enumerable: true,
  21508. configurable: true
  21509. });
  21510. return ClickInfo;
  21511. }());
  21512. /**
  21513. * This class is used by the onRenderingGroupObservable
  21514. */
  21515. var RenderingGroupInfo = /** @class */ (function () {
  21516. function RenderingGroupInfo() {
  21517. }
  21518. /**
  21519. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21520. * This stage will be fired no matter what
  21521. */
  21522. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21523. /**
  21524. * Called before opaque object are rendered.
  21525. * This stage will be fired only if there's 3D Opaque content to render
  21526. */
  21527. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21528. /**
  21529. * Called after the opaque objects are rendered and before the transparent ones
  21530. * This stage will be fired only if there's 3D transparent content to render
  21531. */
  21532. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21533. /**
  21534. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21535. * This stage will be fired no matter what
  21536. */
  21537. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21538. return RenderingGroupInfo;
  21539. }());
  21540. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21541. /**
  21542. * Represents a scene to be rendered by the engine.
  21543. * @see http://doc.babylonjs.com/page.php?p=21911
  21544. */
  21545. var Scene = /** @class */ (function () {
  21546. /**
  21547. * @constructor
  21548. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21549. */
  21550. function Scene(engine) {
  21551. // Members
  21552. this.autoClear = true;
  21553. this.autoClearDepthAndStencil = true;
  21554. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21555. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21556. this._forceWireframe = false;
  21557. this._forcePointsCloud = false;
  21558. this.forceShowBoundingBoxes = false;
  21559. this.animationsEnabled = true;
  21560. this.useConstantAnimationDeltaTime = false;
  21561. this.constantlyUpdateMeshUnderPointer = false;
  21562. this.hoverCursor = "pointer";
  21563. this.defaultCursor = "";
  21564. /**
  21565. * This is used to call preventDefault() on pointer down
  21566. * in order to block unwanted artifacts like system double clicks
  21567. */
  21568. this.preventDefaultOnPointerDown = true;
  21569. // Metadata
  21570. this.metadata = null;
  21571. /**
  21572. * Use this array to add regular expressions used to disable offline support for specific urls
  21573. */
  21574. this.disableOfflineSupportExceptionRules = new Array();
  21575. /**
  21576. * An event triggered when the scene is disposed.
  21577. * @type {BABYLON.Observable}
  21578. */
  21579. this.onDisposeObservable = new BABYLON.Observable();
  21580. this._onDisposeObserver = null;
  21581. /**
  21582. * An event triggered before rendering the scene (right after animations and physics)
  21583. * @type {BABYLON.Observable}
  21584. */
  21585. this.onBeforeRenderObservable = new BABYLON.Observable();
  21586. this._onBeforeRenderObserver = null;
  21587. /**
  21588. * An event triggered after rendering the scene
  21589. * @type {BABYLON.Observable}
  21590. */
  21591. this.onAfterRenderObservable = new BABYLON.Observable();
  21592. this._onAfterRenderObserver = null;
  21593. /**
  21594. * An event triggered before animating the scene
  21595. * @type {BABYLON.Observable}
  21596. */
  21597. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21598. /**
  21599. * An event triggered after animations processing
  21600. * @type {BABYLON.Observable}
  21601. */
  21602. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21603. /**
  21604. * An event triggered before draw calls are ready to be sent
  21605. * @type {BABYLON.Observable}
  21606. */
  21607. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21608. /**
  21609. * An event triggered after draw calls have been sent
  21610. * @type {BABYLON.Observable}
  21611. */
  21612. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21613. /**
  21614. * An event triggered when physic simulation is about to be run
  21615. * @type {BABYLON.Observable}
  21616. */
  21617. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21618. /**
  21619. * An event triggered when physic simulation has been done
  21620. * @type {BABYLON.Observable}
  21621. */
  21622. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21623. /**
  21624. * An event triggered when the scene is ready
  21625. * @type {BABYLON.Observable}
  21626. */
  21627. this.onReadyObservable = new BABYLON.Observable();
  21628. /**
  21629. * An event triggered before rendering a camera
  21630. * @type {BABYLON.Observable}
  21631. */
  21632. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21633. this._onBeforeCameraRenderObserver = null;
  21634. /**
  21635. * An event triggered after rendering a camera
  21636. * @type {BABYLON.Observable}
  21637. */
  21638. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21639. this._onAfterCameraRenderObserver = null;
  21640. /**
  21641. * An event triggered when active meshes evaluation is about to start
  21642. * @type {BABYLON.Observable}
  21643. */
  21644. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21645. /**
  21646. * An event triggered when active meshes evaluation is done
  21647. * @type {BABYLON.Observable}
  21648. */
  21649. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21650. /**
  21651. * An event triggered when particles rendering is about to start
  21652. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21653. * @type {BABYLON.Observable}
  21654. */
  21655. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21656. /**
  21657. * An event triggered when particles rendering is done
  21658. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21659. * @type {BABYLON.Observable}
  21660. */
  21661. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21662. /**
  21663. * An event triggered when sprites rendering is about to start
  21664. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21665. * @type {BABYLON.Observable}
  21666. */
  21667. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21668. /**
  21669. * An event triggered when sprites rendering is done
  21670. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21671. * @type {BABYLON.Observable}
  21672. */
  21673. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21674. /**
  21675. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21676. * @type {BABYLON.Observable}
  21677. */
  21678. this.onDataLoadedObservable = new BABYLON.Observable();
  21679. /**
  21680. * An event triggered when a camera is created
  21681. * @type {BABYLON.Observable}
  21682. */
  21683. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21684. /**
  21685. * An event triggered when a camera is removed
  21686. * @type {BABYLON.Observable}
  21687. */
  21688. this.onCameraRemovedObservable = new BABYLON.Observable();
  21689. /**
  21690. * An event triggered when a light is created
  21691. * @type {BABYLON.Observable}
  21692. */
  21693. this.onNewLightAddedObservable = new BABYLON.Observable();
  21694. /**
  21695. * An event triggered when a light is removed
  21696. * @type {BABYLON.Observable}
  21697. */
  21698. this.onLightRemovedObservable = new BABYLON.Observable();
  21699. /**
  21700. * An event triggered when a geometry is created
  21701. * @type {BABYLON.Observable}
  21702. */
  21703. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21704. /**
  21705. * An event triggered when a geometry is removed
  21706. * @type {BABYLON.Observable}
  21707. */
  21708. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21709. /**
  21710. * An event triggered when a transform node is created
  21711. * @type {BABYLON.Observable}
  21712. */
  21713. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21714. /**
  21715. * An event triggered when a transform node is removed
  21716. * @type {BABYLON.Observable}
  21717. */
  21718. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21719. /**
  21720. * An event triggered when a mesh is created
  21721. * @type {BABYLON.Observable}
  21722. */
  21723. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21724. /**
  21725. * An event triggered when a mesh is removed
  21726. * @type {BABYLON.Observable}
  21727. */
  21728. this.onMeshRemovedObservable = new BABYLON.Observable();
  21729. /**
  21730. * An event triggered when render targets are about to be rendered
  21731. * Can happen multiple times per frame.
  21732. * @type {BABYLON.Observable}
  21733. */
  21734. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21735. /**
  21736. * An event triggered when render targets were rendered.
  21737. * Can happen multiple times per frame.
  21738. * @type {BABYLON.Observable}
  21739. */
  21740. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21741. /**
  21742. * An event triggered before calculating deterministic simulation step
  21743. * @type {BABYLON.Observable}
  21744. */
  21745. this.onBeforeStepObservable = new BABYLON.Observable();
  21746. /**
  21747. * An event triggered after calculating deterministic simulation step
  21748. * @type {BABYLON.Observable}
  21749. */
  21750. this.onAfterStepObservable = new BABYLON.Observable();
  21751. /**
  21752. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21753. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21754. * 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)
  21755. */
  21756. this.onRenderingGroupObservable = new BABYLON.Observable();
  21757. // Animations
  21758. this.animations = [];
  21759. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21760. /**
  21761. * 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).
  21762. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21763. */
  21764. this.onPrePointerObservable = new BABYLON.Observable();
  21765. /**
  21766. * Observable event triggered each time an input event is received from the rendering canvas
  21767. */
  21768. this.onPointerObservable = new BABYLON.Observable();
  21769. this._meshPickProceed = false;
  21770. this._currentPickResult = null;
  21771. this._previousPickResult = null;
  21772. this._totalPointersPressed = 0;
  21773. this._doubleClickOccured = false;
  21774. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21775. this.cameraToUseForPointers = null;
  21776. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21777. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21778. this._startingPointerTime = 0;
  21779. this._previousStartingPointerTime = 0;
  21780. // Deterministic lockstep
  21781. this._timeAccumulator = 0;
  21782. this._currentStepId = 0;
  21783. this._currentInternalStep = 0;
  21784. // Keyboard
  21785. /**
  21786. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21787. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21788. */
  21789. this.onPreKeyboardObservable = new BABYLON.Observable();
  21790. /**
  21791. * Observable event triggered each time an keyboard event is received from the hosting window
  21792. */
  21793. this.onKeyboardObservable = new BABYLON.Observable();
  21794. // Coordinate system
  21795. /**
  21796. * use right-handed coordinate system on this scene.
  21797. * @type {boolean}
  21798. */
  21799. this._useRightHandedSystem = false;
  21800. // Fog
  21801. this._fogEnabled = true;
  21802. this._fogMode = Scene.FOGMODE_NONE;
  21803. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21804. this.fogDensity = 0.1;
  21805. this.fogStart = 0;
  21806. this.fogEnd = 1000.0;
  21807. // Lights
  21808. /**
  21809. * is shadow enabled on this scene.
  21810. * @type {boolean}
  21811. */
  21812. this._shadowsEnabled = true;
  21813. /**
  21814. * is light enabled on this scene.
  21815. * @type {boolean}
  21816. */
  21817. this._lightsEnabled = true;
  21818. /**
  21819. * All of the lights added to this scene.
  21820. */
  21821. this.lights = new Array();
  21822. // Cameras
  21823. /** All of the cameras added to this scene. */
  21824. this.cameras = new Array();
  21825. /** All of the active cameras added to this scene. */
  21826. this.activeCameras = new Array();
  21827. // Meshes
  21828. /**
  21829. * All of the tranform nodes added to this scene.
  21830. */
  21831. this.transformNodes = new Array();
  21832. /**
  21833. * All of the (abstract) meshes added to this scene.
  21834. */
  21835. this.meshes = new Array();
  21836. /**
  21837. * All of the animation groups added to this scene.
  21838. */
  21839. this.animationGroups = new Array();
  21840. // Geometries
  21841. this._geometries = new Array();
  21842. this.materials = new Array();
  21843. this.multiMaterials = new Array();
  21844. // Textures
  21845. this._texturesEnabled = true;
  21846. this.textures = new Array();
  21847. // Particles
  21848. this.particlesEnabled = true;
  21849. this.particleSystems = new Array();
  21850. // Sprites
  21851. this.spritesEnabled = true;
  21852. this.spriteManagers = new Array();
  21853. /**
  21854. * The list of layers (background and foreground) of the scene.
  21855. */
  21856. this.layers = new Array();
  21857. /**
  21858. * The list of effect layers (highlights/glow) contained in the scene.
  21859. */
  21860. this.effectLayers = new Array();
  21861. // Skeletons
  21862. this._skeletonsEnabled = true;
  21863. this.skeletons = new Array();
  21864. // Morph targets
  21865. this.morphTargetManagers = new Array();
  21866. // Lens flares
  21867. this.lensFlaresEnabled = true;
  21868. this.lensFlareSystems = new Array();
  21869. // Collisions
  21870. this.collisionsEnabled = true;
  21871. /** Defines the gravity applied to this scene */
  21872. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21873. // Postprocesses
  21874. this.postProcesses = new Array();
  21875. this.postProcessesEnabled = true;
  21876. // Customs render targets
  21877. this.renderTargetsEnabled = true;
  21878. this.dumpNextRenderTargets = false;
  21879. this.customRenderTargets = new Array();
  21880. // Imported meshes
  21881. this.importedMeshesFiles = new Array();
  21882. // Probes
  21883. this.probesEnabled = true;
  21884. this.reflectionProbes = new Array();
  21885. this._actionManagers = new Array();
  21886. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21887. // Procedural textures
  21888. this.proceduralTexturesEnabled = true;
  21889. this._proceduralTextures = new Array();
  21890. this.soundTracks = new Array();
  21891. this._audioEnabled = true;
  21892. this._headphone = false;
  21893. // Performance counters
  21894. this._totalVertices = new BABYLON.PerfCounter();
  21895. this._activeIndices = new BABYLON.PerfCounter();
  21896. this._activeParticles = new BABYLON.PerfCounter();
  21897. this._activeBones = new BABYLON.PerfCounter();
  21898. this._animationTime = 0;
  21899. this.animationTimeScale = 1;
  21900. this._renderId = 0;
  21901. this._executeWhenReadyTimeoutId = -1;
  21902. this._intermediateRendering = false;
  21903. this._viewUpdateFlag = -1;
  21904. this._projectionUpdateFlag = -1;
  21905. this._alternateViewUpdateFlag = -1;
  21906. this._alternateProjectionUpdateFlag = -1;
  21907. this._toBeDisposed = new BABYLON.SmartArray(256);
  21908. this._activeRequests = new Array();
  21909. this._pendingData = new Array();
  21910. this._isDisposed = false;
  21911. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21912. this._activeMeshes = new BABYLON.SmartArray(256);
  21913. this._processedMaterials = new BABYLON.SmartArray(256);
  21914. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21915. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21916. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21917. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21918. this._activeAnimatables = new Array();
  21919. this._transformMatrix = BABYLON.Matrix.Zero();
  21920. this._useAlternateCameraConfiguration = false;
  21921. this._alternateRendering = false;
  21922. this.requireLightSorting = false;
  21923. this._depthRenderer = {};
  21924. this._activeMeshesFrozen = false;
  21925. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21926. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21927. this._engine.scenes.push(this);
  21928. this._uid = null;
  21929. this._renderingManager = new BABYLON.RenderingManager(this);
  21930. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21931. if (BABYLON.OutlineRenderer) {
  21932. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21933. }
  21934. if (BABYLON.Tools.IsWindowObjectExist()) {
  21935. this.attachControl();
  21936. }
  21937. //simplification queue
  21938. if (BABYLON.SimplificationQueue) {
  21939. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21940. }
  21941. //collision coordinator initialization. For now legacy per default.
  21942. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21943. // Uniform Buffer
  21944. this._createUbo();
  21945. // Default Image processing definition.
  21946. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21947. }
  21948. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21949. /** The fog is deactivated */
  21950. get: function () {
  21951. return Scene._FOGMODE_NONE;
  21952. },
  21953. enumerable: true,
  21954. configurable: true
  21955. });
  21956. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21957. /** The fog density is following an exponential function */
  21958. get: function () {
  21959. return Scene._FOGMODE_EXP;
  21960. },
  21961. enumerable: true,
  21962. configurable: true
  21963. });
  21964. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21965. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21966. get: function () {
  21967. return Scene._FOGMODE_EXP2;
  21968. },
  21969. enumerable: true,
  21970. configurable: true
  21971. });
  21972. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21973. /** The fog density is following a linear function. */
  21974. get: function () {
  21975. return Scene._FOGMODE_LINEAR;
  21976. },
  21977. enumerable: true,
  21978. configurable: true
  21979. });
  21980. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21981. /**
  21982. * Texture used in all pbr material as the reflection texture.
  21983. * As in the majority of the scene they are the same (exception for multi room and so on),
  21984. * this is easier to reference from here than from all the materials.
  21985. */
  21986. get: function () {
  21987. return this._environmentTexture;
  21988. },
  21989. /**
  21990. * Texture used in all pbr material as the reflection texture.
  21991. * As in the majority of the scene they are the same (exception for multi room and so on),
  21992. * this is easier to set here than in all the materials.
  21993. */
  21994. set: function (value) {
  21995. if (this._environmentTexture === value) {
  21996. return;
  21997. }
  21998. this._environmentTexture = value;
  21999. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22005. /**
  22006. * Default image processing configuration used either in the rendering
  22007. * Forward main pass or through the imageProcessingPostProcess if present.
  22008. * As in the majority of the scene they are the same (exception for multi camera),
  22009. * this is easier to reference from here than from all the materials and post process.
  22010. *
  22011. * No setter as we it is a shared configuration, you can set the values instead.
  22012. */
  22013. get: function () {
  22014. return this._imageProcessingConfiguration;
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22020. get: function () {
  22021. return this._forceWireframe;
  22022. },
  22023. set: function (value) {
  22024. if (this._forceWireframe === value) {
  22025. return;
  22026. }
  22027. this._forceWireframe = value;
  22028. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22029. },
  22030. enumerable: true,
  22031. configurable: true
  22032. });
  22033. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22034. get: function () {
  22035. return this._forcePointsCloud;
  22036. },
  22037. set: function (value) {
  22038. if (this._forcePointsCloud === value) {
  22039. return;
  22040. }
  22041. this._forcePointsCloud = value;
  22042. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22043. },
  22044. enumerable: true,
  22045. configurable: true
  22046. });
  22047. Object.defineProperty(Scene.prototype, "onDispose", {
  22048. /** A function to be executed when this scene is disposed. */
  22049. set: function (callback) {
  22050. if (this._onDisposeObserver) {
  22051. this.onDisposeObservable.remove(this._onDisposeObserver);
  22052. }
  22053. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22054. },
  22055. enumerable: true,
  22056. configurable: true
  22057. });
  22058. Object.defineProperty(Scene.prototype, "beforeRender", {
  22059. /** A function to be executed before rendering this scene */
  22060. set: function (callback) {
  22061. if (this._onBeforeRenderObserver) {
  22062. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22063. }
  22064. if (callback) {
  22065. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22066. }
  22067. },
  22068. enumerable: true,
  22069. configurable: true
  22070. });
  22071. Object.defineProperty(Scene.prototype, "afterRender", {
  22072. /** A function to be executed after rendering this scene */
  22073. set: function (callback) {
  22074. if (this._onAfterRenderObserver) {
  22075. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22076. }
  22077. if (callback) {
  22078. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22079. }
  22080. },
  22081. enumerable: true,
  22082. configurable: true
  22083. });
  22084. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22085. set: function (callback) {
  22086. if (this._onBeforeCameraRenderObserver) {
  22087. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22088. }
  22089. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22090. },
  22091. enumerable: true,
  22092. configurable: true
  22093. });
  22094. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22095. set: function (callback) {
  22096. if (this._onAfterCameraRenderObserver) {
  22097. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22098. }
  22099. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22100. },
  22101. enumerable: true,
  22102. configurable: true
  22103. });
  22104. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22105. get: function () {
  22106. if (!this._gamepadManager) {
  22107. this._gamepadManager = new BABYLON.GamepadManager(this);
  22108. }
  22109. return this._gamepadManager;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22115. get: function () {
  22116. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22117. },
  22118. enumerable: true,
  22119. configurable: true
  22120. });
  22121. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22122. get: function () {
  22123. return this._useRightHandedSystem;
  22124. },
  22125. set: function (value) {
  22126. if (this._useRightHandedSystem === value) {
  22127. return;
  22128. }
  22129. this._useRightHandedSystem = value;
  22130. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22131. },
  22132. enumerable: true,
  22133. configurable: true
  22134. });
  22135. Scene.prototype.setStepId = function (newStepId) {
  22136. this._currentStepId = newStepId;
  22137. };
  22138. ;
  22139. Scene.prototype.getStepId = function () {
  22140. return this._currentStepId;
  22141. };
  22142. ;
  22143. Scene.prototype.getInternalStep = function () {
  22144. return this._currentInternalStep;
  22145. };
  22146. ;
  22147. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22148. get: function () {
  22149. return this._fogEnabled;
  22150. },
  22151. /**
  22152. * is fog enabled on this scene.
  22153. */
  22154. set: function (value) {
  22155. if (this._fogEnabled === value) {
  22156. return;
  22157. }
  22158. this._fogEnabled = value;
  22159. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22160. },
  22161. enumerable: true,
  22162. configurable: true
  22163. });
  22164. Object.defineProperty(Scene.prototype, "fogMode", {
  22165. get: function () {
  22166. return this._fogMode;
  22167. },
  22168. set: function (value) {
  22169. if (this._fogMode === value) {
  22170. return;
  22171. }
  22172. this._fogMode = value;
  22173. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22174. },
  22175. enumerable: true,
  22176. configurable: true
  22177. });
  22178. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22179. get: function () {
  22180. return this._shadowsEnabled;
  22181. },
  22182. set: function (value) {
  22183. if (this._shadowsEnabled === value) {
  22184. return;
  22185. }
  22186. this._shadowsEnabled = value;
  22187. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22188. },
  22189. enumerable: true,
  22190. configurable: true
  22191. });
  22192. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22193. get: function () {
  22194. return this._lightsEnabled;
  22195. },
  22196. set: function (value) {
  22197. if (this._lightsEnabled === value) {
  22198. return;
  22199. }
  22200. this._lightsEnabled = value;
  22201. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22202. },
  22203. enumerable: true,
  22204. configurable: true
  22205. });
  22206. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22207. /** The default material used on meshes when no material is affected */
  22208. get: function () {
  22209. if (!this._defaultMaterial) {
  22210. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22211. }
  22212. return this._defaultMaterial;
  22213. },
  22214. /** The default material used on meshes when no material is affected */
  22215. set: function (value) {
  22216. this._defaultMaterial = value;
  22217. },
  22218. enumerable: true,
  22219. configurable: true
  22220. });
  22221. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22222. get: function () {
  22223. return this._texturesEnabled;
  22224. },
  22225. set: function (value) {
  22226. if (this._texturesEnabled === value) {
  22227. return;
  22228. }
  22229. this._texturesEnabled = value;
  22230. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22231. },
  22232. enumerable: true,
  22233. configurable: true
  22234. });
  22235. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22236. get: function () {
  22237. return this._skeletonsEnabled;
  22238. },
  22239. set: function (value) {
  22240. if (this._skeletonsEnabled === value) {
  22241. return;
  22242. }
  22243. this._skeletonsEnabled = value;
  22244. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22245. },
  22246. enumerable: true,
  22247. configurable: true
  22248. });
  22249. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22250. get: function () {
  22251. if (!this._postProcessRenderPipelineManager) {
  22252. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22253. }
  22254. return this._postProcessRenderPipelineManager;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22260. get: function () {
  22261. if (!this._mainSoundTrack) {
  22262. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22263. }
  22264. return this._mainSoundTrack;
  22265. },
  22266. enumerable: true,
  22267. configurable: true
  22268. });
  22269. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22270. get: function () {
  22271. return this._alternateRendering;
  22272. },
  22273. enumerable: true,
  22274. configurable: true
  22275. });
  22276. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22277. get: function () {
  22278. return this._frustumPlanes;
  22279. },
  22280. enumerable: true,
  22281. configurable: true
  22282. });
  22283. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22284. /**
  22285. * Gets the current geometry buffer associated to the scene.
  22286. */
  22287. get: function () {
  22288. return this._geometryBufferRenderer;
  22289. },
  22290. /**
  22291. * Sets the current geometry buffer for the scene.
  22292. */
  22293. set: function (geometryBufferRenderer) {
  22294. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22295. this._geometryBufferRenderer = geometryBufferRenderer;
  22296. }
  22297. },
  22298. enumerable: true,
  22299. configurable: true
  22300. });
  22301. Object.defineProperty(Scene.prototype, "debugLayer", {
  22302. // Properties
  22303. get: function () {
  22304. if (!this._debugLayer) {
  22305. this._debugLayer = new BABYLON.DebugLayer(this);
  22306. }
  22307. return this._debugLayer;
  22308. },
  22309. enumerable: true,
  22310. configurable: true
  22311. });
  22312. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22313. get: function () {
  22314. return this._workerCollisions;
  22315. },
  22316. set: function (enabled) {
  22317. if (!BABYLON.CollisionCoordinatorLegacy) {
  22318. return;
  22319. }
  22320. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22321. this._workerCollisions = enabled;
  22322. if (this.collisionCoordinator) {
  22323. this.collisionCoordinator.destroy();
  22324. }
  22325. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22326. this.collisionCoordinator.init(this);
  22327. },
  22328. enumerable: true,
  22329. configurable: true
  22330. });
  22331. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22332. get: function () {
  22333. return this._selectionOctree;
  22334. },
  22335. enumerable: true,
  22336. configurable: true
  22337. });
  22338. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22339. /**
  22340. * The mesh that is currently under the pointer.
  22341. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22342. */
  22343. get: function () {
  22344. return this._pointerOverMesh;
  22345. },
  22346. enumerable: true,
  22347. configurable: true
  22348. });
  22349. Object.defineProperty(Scene.prototype, "pointerX", {
  22350. /**
  22351. * Current on-screen X position of the pointer
  22352. * @return {number} X position of the pointer
  22353. */
  22354. get: function () {
  22355. return this._pointerX;
  22356. },
  22357. enumerable: true,
  22358. configurable: true
  22359. });
  22360. Object.defineProperty(Scene.prototype, "pointerY", {
  22361. /**
  22362. * Current on-screen Y position of the pointer
  22363. * @return {number} Y position of the pointer
  22364. */
  22365. get: function () {
  22366. return this._pointerY;
  22367. },
  22368. enumerable: true,
  22369. configurable: true
  22370. });
  22371. Scene.prototype.getCachedMaterial = function () {
  22372. return this._cachedMaterial;
  22373. };
  22374. Scene.prototype.getCachedEffect = function () {
  22375. return this._cachedEffect;
  22376. };
  22377. Scene.prototype.getCachedVisibility = function () {
  22378. return this._cachedVisibility;
  22379. };
  22380. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22381. if (visibility === void 0) { visibility = 1; }
  22382. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22383. };
  22384. Scene.prototype.getBoundingBoxRenderer = function () {
  22385. if (!this._boundingBoxRenderer) {
  22386. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22387. }
  22388. return this._boundingBoxRenderer;
  22389. };
  22390. Scene.prototype.getOutlineRenderer = function () {
  22391. return this._outlineRenderer;
  22392. };
  22393. Scene.prototype.getEngine = function () {
  22394. return this._engine;
  22395. };
  22396. Scene.prototype.getTotalVertices = function () {
  22397. return this._totalVertices.current;
  22398. };
  22399. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22400. get: function () {
  22401. return this._totalVertices;
  22402. },
  22403. enumerable: true,
  22404. configurable: true
  22405. });
  22406. Scene.prototype.getActiveIndices = function () {
  22407. return this._activeIndices.current;
  22408. };
  22409. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22410. get: function () {
  22411. return this._activeIndices;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Scene.prototype.getActiveParticles = function () {
  22417. return this._activeParticles.current;
  22418. };
  22419. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22420. get: function () {
  22421. return this._activeParticles;
  22422. },
  22423. enumerable: true,
  22424. configurable: true
  22425. });
  22426. Scene.prototype.getActiveBones = function () {
  22427. return this._activeBones.current;
  22428. };
  22429. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22430. get: function () {
  22431. return this._activeBones;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. // Stats
  22437. Scene.prototype.getInterFramePerfCounter = function () {
  22438. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22439. return 0;
  22440. };
  22441. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22442. get: function () {
  22443. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22444. return null;
  22445. },
  22446. enumerable: true,
  22447. configurable: true
  22448. });
  22449. Scene.prototype.getLastFrameDuration = function () {
  22450. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22451. return 0;
  22452. };
  22453. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22454. get: function () {
  22455. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22456. return null;
  22457. },
  22458. enumerable: true,
  22459. configurable: true
  22460. });
  22461. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22462. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22463. return 0;
  22464. };
  22465. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22466. get: function () {
  22467. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22468. return null;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. Scene.prototype.getActiveMeshes = function () {
  22474. return this._activeMeshes;
  22475. };
  22476. Scene.prototype.getRenderTargetsDuration = function () {
  22477. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22478. return 0;
  22479. };
  22480. Scene.prototype.getRenderDuration = function () {
  22481. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22482. return 0;
  22483. };
  22484. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22485. get: function () {
  22486. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22487. return null;
  22488. },
  22489. enumerable: true,
  22490. configurable: true
  22491. });
  22492. Scene.prototype.getParticlesDuration = function () {
  22493. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22494. return 0;
  22495. };
  22496. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22497. get: function () {
  22498. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22499. return null;
  22500. },
  22501. enumerable: true,
  22502. configurable: true
  22503. });
  22504. Scene.prototype.getSpritesDuration = function () {
  22505. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22506. return 0;
  22507. };
  22508. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22509. get: function () {
  22510. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22511. return null;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. Scene.prototype.getAnimationRatio = function () {
  22517. return this._animationRatio;
  22518. };
  22519. Scene.prototype.getRenderId = function () {
  22520. return this._renderId;
  22521. };
  22522. Scene.prototype.incrementRenderId = function () {
  22523. this._renderId++;
  22524. };
  22525. Scene.prototype._updatePointerPosition = function (evt) {
  22526. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22527. if (!canvasRect) {
  22528. return;
  22529. }
  22530. this._pointerX = evt.clientX - canvasRect.left;
  22531. this._pointerY = evt.clientY - canvasRect.top;
  22532. this._unTranslatedPointerX = this._pointerX;
  22533. this._unTranslatedPointerY = this._pointerY;
  22534. };
  22535. Scene.prototype._createUbo = function () {
  22536. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22537. this._sceneUbo.addUniform("viewProjection", 16);
  22538. this._sceneUbo.addUniform("view", 16);
  22539. };
  22540. Scene.prototype._createAlternateUbo = function () {
  22541. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22542. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22543. this._alternateSceneUbo.addUniform("view", 16);
  22544. };
  22545. // Pointers handling
  22546. /**
  22547. * Use this method to simulate a pointer move on a mesh
  22548. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22549. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22550. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22551. */
  22552. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22553. var evt = new PointerEvent("pointermove", pointerEventInit);
  22554. return this._processPointerMove(pickResult, evt);
  22555. };
  22556. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22557. var canvas = this._engine.getRenderingCanvas();
  22558. if (!canvas) {
  22559. return this;
  22560. }
  22561. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22562. this.setPointerOverSprite(null);
  22563. this.setPointerOverMesh(pickResult.pickedMesh);
  22564. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22565. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22566. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22567. }
  22568. else {
  22569. canvas.style.cursor = this.hoverCursor;
  22570. }
  22571. }
  22572. else {
  22573. canvas.style.cursor = this.defaultCursor;
  22574. }
  22575. }
  22576. else {
  22577. this.setPointerOverMesh(null);
  22578. // Sprites
  22579. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22580. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22581. this.setPointerOverSprite(pickResult.pickedSprite);
  22582. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22583. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22584. }
  22585. else {
  22586. canvas.style.cursor = this.hoverCursor;
  22587. }
  22588. }
  22589. else {
  22590. this.setPointerOverSprite(null);
  22591. // Restore pointer
  22592. canvas.style.cursor = this.defaultCursor;
  22593. }
  22594. }
  22595. if (pickResult) {
  22596. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22597. if (this.onPointerMove) {
  22598. this.onPointerMove(evt, pickResult, type);
  22599. }
  22600. if (this.onPointerObservable.hasObservers()) {
  22601. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22602. this.onPointerObservable.notifyObservers(pi, type);
  22603. }
  22604. }
  22605. return this;
  22606. };
  22607. /**
  22608. * Use this method to simulate a pointer down on a mesh
  22609. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22610. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22611. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22612. */
  22613. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22614. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22615. return this._processPointerDown(pickResult, evt);
  22616. };
  22617. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22618. var _this = this;
  22619. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22620. this._pickedDownMesh = pickResult.pickedMesh;
  22621. var actionManager = pickResult.pickedMesh.actionManager;
  22622. if (actionManager) {
  22623. if (actionManager.hasPickTriggers) {
  22624. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22625. switch (evt.button) {
  22626. case 0:
  22627. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22628. break;
  22629. case 1:
  22630. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22631. break;
  22632. case 2:
  22633. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22634. break;
  22635. }
  22636. }
  22637. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22638. window.setTimeout(function () {
  22639. 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);
  22640. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22641. if (_this._totalPointersPressed !== 0 &&
  22642. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22643. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22644. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22645. _this._startingPointerTime = 0;
  22646. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22647. }
  22648. }
  22649. }, Scene.LongPressDelay);
  22650. }
  22651. }
  22652. }
  22653. if (pickResult) {
  22654. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22655. if (this.onPointerDown) {
  22656. this.onPointerDown(evt, pickResult, type);
  22657. }
  22658. if (this.onPointerObservable.hasObservers()) {
  22659. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22660. this.onPointerObservable.notifyObservers(pi, type);
  22661. }
  22662. }
  22663. return this;
  22664. };
  22665. /**
  22666. * Use this method to simulate a pointer up on a mesh
  22667. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22668. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22669. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22670. */
  22671. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22672. var evt = new PointerEvent("pointerup", pointerEventInit);
  22673. var clickInfo = new ClickInfo();
  22674. clickInfo.singleClick = true;
  22675. clickInfo.ignore = true;
  22676. return this._processPointerUp(pickResult, evt, clickInfo);
  22677. };
  22678. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22679. if (pickResult && pickResult && pickResult.pickedMesh) {
  22680. this._pickedUpMesh = pickResult.pickedMesh;
  22681. if (this._pickedDownMesh === this._pickedUpMesh) {
  22682. if (this.onPointerPick) {
  22683. this.onPointerPick(evt, pickResult);
  22684. }
  22685. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22686. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22687. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22688. this.onPointerObservable.notifyObservers(pi, type_1);
  22689. }
  22690. }
  22691. if (pickResult.pickedMesh.actionManager) {
  22692. if (clickInfo.ignore) {
  22693. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22694. }
  22695. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22696. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22697. }
  22698. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22699. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22700. }
  22701. }
  22702. }
  22703. if (this._pickedDownMesh &&
  22704. this._pickedDownMesh.actionManager &&
  22705. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22706. this._pickedDownMesh !== this._pickedUpMesh) {
  22707. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22708. }
  22709. var type = BABYLON.PointerEventTypes.POINTERUP;
  22710. if (this.onPointerObservable.hasObservers()) {
  22711. if (!clickInfo.ignore) {
  22712. if (!clickInfo.hasSwiped) {
  22713. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22714. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22715. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22716. this.onPointerObservable.notifyObservers(pi, type_2);
  22717. }
  22718. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22719. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22720. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22721. this.onPointerObservable.notifyObservers(pi, type_3);
  22722. }
  22723. }
  22724. }
  22725. else {
  22726. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22727. this.onPointerObservable.notifyObservers(pi, type);
  22728. }
  22729. }
  22730. if (this.onPointerUp) {
  22731. this.onPointerUp(evt, pickResult, type);
  22732. }
  22733. return this;
  22734. };
  22735. /**
  22736. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22737. * @param attachUp defines if you want to attach events to pointerup
  22738. * @param attachDown defines if you want to attach events to pointerdown
  22739. * @param attachMove defines if you want to attach events to pointermove
  22740. */
  22741. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22742. var _this = this;
  22743. if (attachUp === void 0) { attachUp = true; }
  22744. if (attachDown === void 0) { attachDown = true; }
  22745. if (attachMove === void 0) { attachMove = true; }
  22746. this._initActionManager = function (act, clickInfo) {
  22747. if (!_this._meshPickProceed) {
  22748. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22749. _this._currentPickResult = pickResult;
  22750. if (pickResult) {
  22751. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22752. }
  22753. _this._meshPickProceed = true;
  22754. }
  22755. return act;
  22756. };
  22757. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22758. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22759. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22760. btn !== _this._previousButtonPressed) {
  22761. _this._doubleClickOccured = false;
  22762. clickInfo.singleClick = true;
  22763. clickInfo.ignore = false;
  22764. cb(clickInfo, _this._currentPickResult);
  22765. }
  22766. };
  22767. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22768. var clickInfo = new ClickInfo();
  22769. _this._currentPickResult = null;
  22770. var act = null;
  22771. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22772. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22773. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22774. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22775. act = _this._initActionManager(act, clickInfo);
  22776. if (act)
  22777. checkPicking = act.hasPickTriggers;
  22778. }
  22779. if (checkPicking) {
  22780. var btn = evt.button;
  22781. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22782. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22783. if (!clickInfo.hasSwiped) {
  22784. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22785. if (!checkSingleClickImmediately) {
  22786. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22787. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22788. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22789. act = _this._initActionManager(act, clickInfo);
  22790. if (act)
  22791. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22792. }
  22793. }
  22794. if (checkSingleClickImmediately) {
  22795. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22796. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22797. btn !== _this._previousButtonPressed) {
  22798. clickInfo.singleClick = true;
  22799. cb(clickInfo, _this._currentPickResult);
  22800. }
  22801. }
  22802. else {
  22803. // wait that no double click has been raised during the double click delay
  22804. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22805. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22806. }
  22807. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22808. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22809. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22810. act = _this._initActionManager(act, clickInfo);
  22811. if (act)
  22812. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22813. }
  22814. if (checkDoubleClick) {
  22815. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22816. if (btn === _this._previousButtonPressed &&
  22817. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22818. !_this._doubleClickOccured) {
  22819. // pointer has not moved for 2 clicks, it's a double click
  22820. if (!clickInfo.hasSwiped &&
  22821. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22822. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22823. _this._previousStartingPointerTime = 0;
  22824. _this._doubleClickOccured = true;
  22825. clickInfo.doubleClick = true;
  22826. clickInfo.ignore = false;
  22827. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22828. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22829. }
  22830. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22831. cb(clickInfo, _this._currentPickResult);
  22832. }
  22833. else {
  22834. _this._doubleClickOccured = false;
  22835. _this._previousStartingPointerTime = _this._startingPointerTime;
  22836. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22837. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22838. _this._previousButtonPressed = btn;
  22839. if (Scene.ExclusiveDoubleClickMode) {
  22840. if (_this._previousDelayedSimpleClickTimeout) {
  22841. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22842. }
  22843. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22844. cb(clickInfo, _this._previousPickResult);
  22845. }
  22846. else {
  22847. cb(clickInfo, _this._currentPickResult);
  22848. }
  22849. }
  22850. }
  22851. else {
  22852. _this._doubleClickOccured = false;
  22853. _this._previousStartingPointerTime = _this._startingPointerTime;
  22854. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22855. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22856. _this._previousButtonPressed = btn;
  22857. }
  22858. }
  22859. }
  22860. }
  22861. clickInfo.ignore = true;
  22862. cb(clickInfo, _this._currentPickResult);
  22863. };
  22864. this._spritePredicate = function (sprite) {
  22865. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22866. };
  22867. this._onPointerMove = function (evt) {
  22868. _this._updatePointerPosition(evt);
  22869. // PreObservable support
  22870. if (_this.onPrePointerObservable.hasObservers()) {
  22871. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22872. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22873. _this.onPrePointerObservable.notifyObservers(pi, type);
  22874. if (pi.skipOnPointerObservable) {
  22875. return;
  22876. }
  22877. }
  22878. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22879. return;
  22880. }
  22881. if (!_this.pointerMovePredicate) {
  22882. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22883. }
  22884. // Meshes
  22885. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22886. _this._processPointerMove(pickResult, evt);
  22887. };
  22888. this._onPointerDown = function (evt) {
  22889. _this._totalPointersPressed++;
  22890. _this._pickedDownMesh = null;
  22891. _this._meshPickProceed = false;
  22892. _this._updatePointerPosition(evt);
  22893. if (_this.preventDefaultOnPointerDown && canvas) {
  22894. evt.preventDefault();
  22895. canvas.focus();
  22896. }
  22897. // PreObservable support
  22898. if (_this.onPrePointerObservable.hasObservers()) {
  22899. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22900. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22901. _this.onPrePointerObservable.notifyObservers(pi, type);
  22902. if (pi.skipOnPointerObservable) {
  22903. return;
  22904. }
  22905. }
  22906. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22907. return;
  22908. }
  22909. _this._startingPointerPosition.x = _this._pointerX;
  22910. _this._startingPointerPosition.y = _this._pointerY;
  22911. _this._startingPointerTime = new Date().getTime();
  22912. if (!_this.pointerDownPredicate) {
  22913. _this.pointerDownPredicate = function (mesh) {
  22914. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22915. };
  22916. }
  22917. // Meshes
  22918. _this._pickedDownMesh = null;
  22919. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22920. _this._processPointerDown(pickResult, evt);
  22921. // Sprites
  22922. _this._pickedDownSprite = null;
  22923. if (_this.spriteManagers.length > 0) {
  22924. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22925. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22926. if (pickResult.pickedSprite.actionManager) {
  22927. _this._pickedDownSprite = pickResult.pickedSprite;
  22928. switch (evt.button) {
  22929. case 0:
  22930. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22931. break;
  22932. case 1:
  22933. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22934. break;
  22935. case 2:
  22936. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22937. break;
  22938. }
  22939. if (pickResult.pickedSprite.actionManager) {
  22940. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22941. }
  22942. }
  22943. }
  22944. }
  22945. };
  22946. this._onPointerUp = function (evt) {
  22947. if (_this._totalPointersPressed === 0) {
  22948. return; // So we need to test it the pointer down was pressed before.
  22949. }
  22950. _this._totalPointersPressed--;
  22951. _this._pickedUpMesh = null;
  22952. _this._meshPickProceed = false;
  22953. _this._updatePointerPosition(evt);
  22954. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22955. // PreObservable support
  22956. if (_this.onPrePointerObservable.hasObservers()) {
  22957. if (!clickInfo.ignore) {
  22958. if (!clickInfo.hasSwiped) {
  22959. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22960. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22961. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22962. _this.onPrePointerObservable.notifyObservers(pi, type);
  22963. if (pi.skipOnPointerObservable) {
  22964. return;
  22965. }
  22966. }
  22967. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22968. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22969. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22970. _this.onPrePointerObservable.notifyObservers(pi, type);
  22971. if (pi.skipOnPointerObservable) {
  22972. return;
  22973. }
  22974. }
  22975. }
  22976. }
  22977. else {
  22978. var type = BABYLON.PointerEventTypes.POINTERUP;
  22979. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22980. _this.onPrePointerObservable.notifyObservers(pi, type);
  22981. if (pi.skipOnPointerObservable) {
  22982. return;
  22983. }
  22984. }
  22985. }
  22986. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22987. return;
  22988. }
  22989. if (!_this.pointerUpPredicate) {
  22990. _this.pointerUpPredicate = function (mesh) {
  22991. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22992. };
  22993. }
  22994. // Meshes
  22995. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22996. _this._initActionManager(null, clickInfo);
  22997. }
  22998. if (!pickResult) {
  22999. pickResult = _this._currentPickResult;
  23000. }
  23001. _this._processPointerUp(pickResult, evt, clickInfo);
  23002. // Sprites
  23003. if (_this.spriteManagers.length > 0) {
  23004. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23005. if (spritePickResult) {
  23006. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23007. if (spritePickResult.pickedSprite.actionManager) {
  23008. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23009. if (spritePickResult.pickedSprite.actionManager) {
  23010. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23011. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23012. }
  23013. }
  23014. }
  23015. }
  23016. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23017. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23018. }
  23019. }
  23020. }
  23021. _this._previousPickResult = _this._currentPickResult;
  23022. });
  23023. };
  23024. this._onKeyDown = function (evt) {
  23025. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23026. if (_this.onPreKeyboardObservable.hasObservers()) {
  23027. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23028. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23029. if (pi.skipOnPointerObservable) {
  23030. return;
  23031. }
  23032. }
  23033. if (_this.onKeyboardObservable.hasObservers()) {
  23034. var pi = new BABYLON.KeyboardInfo(type, evt);
  23035. _this.onKeyboardObservable.notifyObservers(pi, type);
  23036. }
  23037. if (_this.actionManager) {
  23038. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23039. }
  23040. };
  23041. this._onKeyUp = function (evt) {
  23042. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23043. if (_this.onPreKeyboardObservable.hasObservers()) {
  23044. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23045. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23046. if (pi.skipOnPointerObservable) {
  23047. return;
  23048. }
  23049. }
  23050. if (_this.onKeyboardObservable.hasObservers()) {
  23051. var pi = new BABYLON.KeyboardInfo(type, evt);
  23052. _this.onKeyboardObservable.notifyObservers(pi, type);
  23053. }
  23054. if (_this.actionManager) {
  23055. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23056. }
  23057. };
  23058. var engine = this.getEngine();
  23059. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23060. if (!canvas) {
  23061. return;
  23062. }
  23063. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23064. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23065. });
  23066. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23067. if (!canvas) {
  23068. return;
  23069. }
  23070. canvas.removeEventListener("keydown", _this._onKeyDown);
  23071. canvas.removeEventListener("keyup", _this._onKeyUp);
  23072. });
  23073. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23074. var canvas = this._engine.getRenderingCanvas();
  23075. if (!canvas) {
  23076. return;
  23077. }
  23078. if (attachMove) {
  23079. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23080. // Wheel
  23081. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23082. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23083. }
  23084. if (attachDown) {
  23085. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23086. }
  23087. if (attachUp) {
  23088. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23089. }
  23090. canvas.tabIndex = 1;
  23091. };
  23092. Scene.prototype.detachControl = function () {
  23093. var engine = this.getEngine();
  23094. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23095. var canvas = engine.getRenderingCanvas();
  23096. if (!canvas) {
  23097. return;
  23098. }
  23099. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23100. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23101. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23102. if (this._onCanvasBlurObserver) {
  23103. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23104. }
  23105. if (this._onCanvasFocusObserver) {
  23106. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23107. }
  23108. // Wheel
  23109. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23110. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23111. // Keyboard
  23112. canvas.removeEventListener("keydown", this._onKeyDown);
  23113. canvas.removeEventListener("keyup", this._onKeyUp);
  23114. // Observables
  23115. this.onKeyboardObservable.clear();
  23116. this.onPreKeyboardObservable.clear();
  23117. this.onPointerObservable.clear();
  23118. this.onPrePointerObservable.clear();
  23119. };
  23120. /**
  23121. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23122. * Delay loaded resources are not taking in account
  23123. * @return true if all required resources are ready
  23124. */
  23125. Scene.prototype.isReady = function () {
  23126. if (this._isDisposed) {
  23127. return false;
  23128. }
  23129. if (this._pendingData.length > 0) {
  23130. return false;
  23131. }
  23132. var index;
  23133. var engine = this.getEngine();
  23134. // Geometries
  23135. for (index = 0; index < this._geometries.length; index++) {
  23136. var geometry = this._geometries[index];
  23137. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23138. return false;
  23139. }
  23140. }
  23141. // Meshes
  23142. for (index = 0; index < this.meshes.length; index++) {
  23143. var mesh = this.meshes[index];
  23144. if (!mesh.isEnabled()) {
  23145. continue;
  23146. }
  23147. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23148. continue;
  23149. }
  23150. if (!mesh.isReady(true)) {
  23151. return false;
  23152. }
  23153. // Effect layers
  23154. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23155. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23156. var layer = _a[_i];
  23157. if (!layer.hasMesh(mesh)) {
  23158. continue;
  23159. }
  23160. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23161. var subMesh = _c[_b];
  23162. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23163. return false;
  23164. }
  23165. }
  23166. }
  23167. }
  23168. // Post-processes
  23169. if (this.activeCameras && this.activeCameras.length > 0) {
  23170. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  23171. var camera = _e[_d];
  23172. if (!camera.isReady(true)) {
  23173. return false;
  23174. }
  23175. }
  23176. }
  23177. else if (this.activeCamera) {
  23178. if (!this.activeCamera.isReady(true)) {
  23179. return false;
  23180. }
  23181. }
  23182. // Particles
  23183. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  23184. var particleSystem = _g[_f];
  23185. if (!particleSystem.isReady()) {
  23186. return false;
  23187. }
  23188. }
  23189. return true;
  23190. };
  23191. Scene.prototype.resetCachedMaterial = function () {
  23192. this._cachedMaterial = null;
  23193. this._cachedEffect = null;
  23194. this._cachedVisibility = null;
  23195. };
  23196. Scene.prototype.registerBeforeRender = function (func) {
  23197. this.onBeforeRenderObservable.add(func);
  23198. };
  23199. Scene.prototype.unregisterBeforeRender = function (func) {
  23200. this.onBeforeRenderObservable.removeCallback(func);
  23201. };
  23202. Scene.prototype.registerAfterRender = function (func) {
  23203. this.onAfterRenderObservable.add(func);
  23204. };
  23205. Scene.prototype.unregisterAfterRender = function (func) {
  23206. this.onAfterRenderObservable.removeCallback(func);
  23207. };
  23208. Scene.prototype._executeOnceBeforeRender = function (func) {
  23209. var _this = this;
  23210. var execFunc = function () {
  23211. func();
  23212. setTimeout(function () {
  23213. _this.unregisterBeforeRender(execFunc);
  23214. });
  23215. };
  23216. this.registerBeforeRender(execFunc);
  23217. };
  23218. /**
  23219. * The provided function will run before render once and will be disposed afterwards.
  23220. * A timeout delay can be provided so that the function will be executed in N ms.
  23221. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23222. * @param func The function to be executed.
  23223. * @param timeout optional delay in ms
  23224. */
  23225. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23226. var _this = this;
  23227. if (timeout !== undefined) {
  23228. setTimeout(function () {
  23229. _this._executeOnceBeforeRender(func);
  23230. }, timeout);
  23231. }
  23232. else {
  23233. this._executeOnceBeforeRender(func);
  23234. }
  23235. };
  23236. Scene.prototype._addPendingData = function (data) {
  23237. this._pendingData.push(data);
  23238. };
  23239. Scene.prototype._removePendingData = function (data) {
  23240. var wasLoading = this.isLoading;
  23241. var index = this._pendingData.indexOf(data);
  23242. if (index !== -1) {
  23243. this._pendingData.splice(index, 1);
  23244. }
  23245. if (wasLoading && !this.isLoading) {
  23246. this.onDataLoadedObservable.notifyObservers(this);
  23247. }
  23248. };
  23249. Scene.prototype.getWaitingItemsCount = function () {
  23250. return this._pendingData.length;
  23251. };
  23252. Object.defineProperty(Scene.prototype, "isLoading", {
  23253. get: function () {
  23254. return this._pendingData.length > 0;
  23255. },
  23256. enumerable: true,
  23257. configurable: true
  23258. });
  23259. /**
  23260. * Registers a function to be executed when the scene is ready.
  23261. * @param {Function} func - the function to be executed.
  23262. */
  23263. Scene.prototype.executeWhenReady = function (func) {
  23264. var _this = this;
  23265. this.onReadyObservable.add(func);
  23266. if (this._executeWhenReadyTimeoutId !== -1) {
  23267. return;
  23268. }
  23269. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23270. _this._checkIsReady();
  23271. }, 150);
  23272. };
  23273. /**
  23274. * Returns a promise that resolves when the scene is ready.
  23275. * @returns A promise that resolves when the scene is ready.
  23276. */
  23277. Scene.prototype.whenReadyAsync = function () {
  23278. var _this = this;
  23279. return new Promise(function (resolve) {
  23280. _this.executeWhenReady(function () {
  23281. resolve();
  23282. });
  23283. });
  23284. };
  23285. Scene.prototype._checkIsReady = function () {
  23286. var _this = this;
  23287. if (this.isReady()) {
  23288. this.onReadyObservable.notifyObservers(this);
  23289. this.onReadyObservable.clear();
  23290. this._executeWhenReadyTimeoutId = -1;
  23291. return;
  23292. }
  23293. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23294. _this._checkIsReady();
  23295. }, 150);
  23296. };
  23297. // Animations
  23298. /**
  23299. * Will start the animation sequence of a given target
  23300. * @param target defines the target
  23301. * @param from defines from which frame should animation start
  23302. * @param to defines until which frame should animation run.
  23303. * @param weight defines the weight to apply to the animation (1.0 by default)
  23304. * @param loop defines if the animation loops
  23305. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23306. * @param onAnimationEnd defines the function to be executed when the animation ends
  23307. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23308. * @returns the animatable object created for this animation
  23309. */
  23310. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23311. if (weight === void 0) { weight = 1.0; }
  23312. if (speedRatio === void 0) { speedRatio = 1.0; }
  23313. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23314. returnedAnimatable.weight = weight;
  23315. return returnedAnimatable;
  23316. };
  23317. /**
  23318. * Will start the animation sequence of a given target
  23319. * @param target defines the target
  23320. * @param from defines from which frame should animation start
  23321. * @param to defines until which frame should animation run.
  23322. * @param loop defines if the animation loops
  23323. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23324. * @param onAnimationEnd defines the function to be executed when the animation ends
  23325. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23326. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23327. * @returns the animatable object created for this animation
  23328. */
  23329. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23330. if (speedRatio === void 0) { speedRatio = 1.0; }
  23331. if (stopCurrent === void 0) { stopCurrent = true; }
  23332. if (from > to && speedRatio > 0) {
  23333. speedRatio *= -1;
  23334. }
  23335. if (stopCurrent) {
  23336. this.stopAnimation(target);
  23337. }
  23338. if (!animatable) {
  23339. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23340. }
  23341. // Local animations
  23342. if (target.animations) {
  23343. animatable.appendAnimations(target, target.animations);
  23344. }
  23345. // Children animations
  23346. if (target.getAnimatables) {
  23347. var animatables = target.getAnimatables();
  23348. for (var index = 0; index < animatables.length; index++) {
  23349. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23350. }
  23351. }
  23352. animatable.reset();
  23353. return animatable;
  23354. };
  23355. /**
  23356. * Begin a new animation on a given node
  23357. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23358. * @param {BABYLON.Animation[]} defines the list of animations to start
  23359. * @param {number} from defines the initial value
  23360. * @param {number} to defines the final value
  23361. * @param {boolean} loop defines if you want animation to loop (off by default)
  23362. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23363. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23364. * @returns the list of created animatables
  23365. */
  23366. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23367. if (speedRatio === undefined) {
  23368. speedRatio = 1.0;
  23369. }
  23370. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23371. return animatable;
  23372. };
  23373. /**
  23374. * Begin a new animation on a given node and its hierarchy
  23375. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23376. * @param {boolean} 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.
  23377. * @param {BABYLON.Animation[]} defines the list of animations to start
  23378. * @param {number} from defines the initial value
  23379. * @param {number} to defines the final value
  23380. * @param {boolean} loop defines if you want animation to loop (off by default)
  23381. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23382. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23383. * @returns the list of animatables created for all nodes
  23384. */
  23385. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23386. var children = target.getDescendants(directDescendantsOnly);
  23387. var result = [];
  23388. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23389. var child = children_1[_i];
  23390. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23391. }
  23392. return result;
  23393. };
  23394. Scene.prototype.getAnimatableByTarget = function (target) {
  23395. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23396. if (this._activeAnimatables[index].target === target) {
  23397. return this._activeAnimatables[index];
  23398. }
  23399. }
  23400. return null;
  23401. };
  23402. /**
  23403. * Gets all animatables associated with a given target
  23404. * @param target defines the target to look animatables for
  23405. * @returns an array of Animatables
  23406. */
  23407. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  23408. var result = [];
  23409. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23410. if (this._activeAnimatables[index].target === target) {
  23411. result.push(this._activeAnimatables[index]);
  23412. }
  23413. }
  23414. return result;
  23415. };
  23416. Object.defineProperty(Scene.prototype, "animatables", {
  23417. get: function () {
  23418. return this._activeAnimatables;
  23419. },
  23420. enumerable: true,
  23421. configurable: true
  23422. });
  23423. /**
  23424. * Will stop the animation of the given target
  23425. * @param target - the target
  23426. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  23427. */
  23428. Scene.prototype.stopAnimation = function (target, animationName) {
  23429. var animatables = this.getAllAnimatablesByTarget(target);
  23430. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  23431. var animatable = animatables_1[_i];
  23432. animatable.stop(animationName);
  23433. }
  23434. };
  23435. /**
  23436. * Stops and removes all animations that have been applied to the scene
  23437. */
  23438. Scene.prototype.stopAllAnimations = function () {
  23439. if (this._activeAnimatables) {
  23440. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23441. this._activeAnimatables[i].stop();
  23442. }
  23443. this._activeAnimatables = [];
  23444. }
  23445. };
  23446. Scene.prototype._animate = function () {
  23447. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23448. return;
  23449. }
  23450. // Getting time
  23451. var now = BABYLON.Tools.Now;
  23452. if (!this._animationTimeLast) {
  23453. if (this._pendingData.length > 0) {
  23454. return;
  23455. }
  23456. this._animationTimeLast = now;
  23457. }
  23458. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23459. this._animationTime += deltaTime;
  23460. this._animationTimeLast = now;
  23461. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23462. this._activeAnimatables[index]._animate(this._animationTime);
  23463. }
  23464. // Late animation bindings
  23465. this._processLateAnimationBindings();
  23466. };
  23467. /** @ignore */
  23468. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23469. var target = runtimeAnimation.target;
  23470. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23471. if (!target._lateAnimationHolders) {
  23472. target._lateAnimationHolders = {};
  23473. }
  23474. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23475. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23476. totalWeight: 0,
  23477. animations: []
  23478. };
  23479. }
  23480. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23481. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23482. };
  23483. Scene.prototype._processLateAnimationBindings = function () {
  23484. if (!this._registeredForLateAnimationBindings.length) {
  23485. return;
  23486. }
  23487. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23488. var target = this._registeredForLateAnimationBindings.data[index];
  23489. for (var path in target._lateAnimationHolders) {
  23490. var holder = target._lateAnimationHolders[path];
  23491. // Sanity check
  23492. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23493. continue;
  23494. }
  23495. var normalizer = 1.0;
  23496. var finalValue = void 0;
  23497. if (holder.totalWeight < 1.0) {
  23498. // We need to mix the original value in
  23499. var originalValue = holder.animations[0].originalValue;
  23500. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23501. }
  23502. else {
  23503. // We need to normalize the weights
  23504. normalizer = holder.totalWeight;
  23505. }
  23506. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23507. var runtimeAnimation = holder.animations[animIndex];
  23508. if (finalValue) {
  23509. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23510. }
  23511. else {
  23512. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23513. }
  23514. }
  23515. runtimeAnimation.target[path] = finalValue;
  23516. }
  23517. target._lateAnimationHolders = {};
  23518. }
  23519. this._registeredForLateAnimationBindings.reset();
  23520. };
  23521. // Matrix
  23522. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23523. this._useAlternateCameraConfiguration = active;
  23524. };
  23525. Scene.prototype.getViewMatrix = function () {
  23526. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23527. };
  23528. Scene.prototype.getProjectionMatrix = function () {
  23529. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23530. };
  23531. Scene.prototype.getTransformMatrix = function () {
  23532. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23533. };
  23534. Scene.prototype.setTransformMatrix = function (view, projection) {
  23535. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23536. return;
  23537. }
  23538. this._viewUpdateFlag = view.updateFlag;
  23539. this._projectionUpdateFlag = projection.updateFlag;
  23540. this._viewMatrix = view;
  23541. this._projectionMatrix = projection;
  23542. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23543. // Update frustum
  23544. if (!this._frustumPlanes) {
  23545. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23546. }
  23547. else {
  23548. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23549. }
  23550. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23551. var otherCamera = this.activeCamera._alternateCamera;
  23552. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23553. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23554. }
  23555. if (this._sceneUbo.useUbo) {
  23556. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23557. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23558. this._sceneUbo.update();
  23559. }
  23560. };
  23561. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23562. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23563. return;
  23564. }
  23565. this._alternateViewUpdateFlag = view.updateFlag;
  23566. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23567. this._alternateViewMatrix = view;
  23568. this._alternateProjectionMatrix = projection;
  23569. if (!this._alternateTransformMatrix) {
  23570. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23571. }
  23572. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23573. if (!this._alternateSceneUbo) {
  23574. this._createAlternateUbo();
  23575. }
  23576. if (this._alternateSceneUbo.useUbo) {
  23577. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23578. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23579. this._alternateSceneUbo.update();
  23580. }
  23581. };
  23582. Scene.prototype.getSceneUniformBuffer = function () {
  23583. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23584. };
  23585. // Methods
  23586. Scene.prototype.getUniqueId = function () {
  23587. var result = Scene._uniqueIdCounter;
  23588. Scene._uniqueIdCounter++;
  23589. return result;
  23590. };
  23591. Scene.prototype.addMesh = function (newMesh) {
  23592. this.meshes.push(newMesh);
  23593. //notify the collision coordinator
  23594. if (this.collisionCoordinator) {
  23595. this.collisionCoordinator.onMeshAdded(newMesh);
  23596. }
  23597. newMesh._resyncLightSources();
  23598. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23599. };
  23600. Scene.prototype.removeMesh = function (toRemove) {
  23601. var index = this.meshes.indexOf(toRemove);
  23602. if (index !== -1) {
  23603. // Remove from the scene if mesh found
  23604. this.meshes.splice(index, 1);
  23605. }
  23606. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23607. return index;
  23608. };
  23609. Scene.prototype.addTransformNode = function (newTransformNode) {
  23610. this.transformNodes.push(newTransformNode);
  23611. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23612. };
  23613. Scene.prototype.removeTransformNode = function (toRemove) {
  23614. var index = this.transformNodes.indexOf(toRemove);
  23615. if (index !== -1) {
  23616. // Remove from the scene if found
  23617. this.transformNodes.splice(index, 1);
  23618. }
  23619. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23620. return index;
  23621. };
  23622. Scene.prototype.removeSkeleton = function (toRemove) {
  23623. var index = this.skeletons.indexOf(toRemove);
  23624. if (index !== -1) {
  23625. // Remove from the scene if found
  23626. this.skeletons.splice(index, 1);
  23627. }
  23628. return index;
  23629. };
  23630. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23631. var index = this.morphTargetManagers.indexOf(toRemove);
  23632. if (index !== -1) {
  23633. // Remove from the scene if found
  23634. this.morphTargetManagers.splice(index, 1);
  23635. }
  23636. return index;
  23637. };
  23638. Scene.prototype.removeLight = function (toRemove) {
  23639. var index = this.lights.indexOf(toRemove);
  23640. if (index !== -1) {
  23641. // Remove from meshes
  23642. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23643. var mesh = _a[_i];
  23644. mesh._removeLightSource(toRemove);
  23645. }
  23646. // Remove from the scene if mesh found
  23647. this.lights.splice(index, 1);
  23648. this.sortLightsByPriority();
  23649. }
  23650. this.onLightRemovedObservable.notifyObservers(toRemove);
  23651. return index;
  23652. };
  23653. Scene.prototype.removeCamera = function (toRemove) {
  23654. var index = this.cameras.indexOf(toRemove);
  23655. if (index !== -1) {
  23656. // Remove from the scene if mesh found
  23657. this.cameras.splice(index, 1);
  23658. }
  23659. // Remove from activeCameras
  23660. var index2 = this.activeCameras.indexOf(toRemove);
  23661. if (index2 !== -1) {
  23662. // Remove from the scene if mesh found
  23663. this.activeCameras.splice(index2, 1);
  23664. }
  23665. // Reset the activeCamera
  23666. if (this.activeCamera === toRemove) {
  23667. if (this.cameras.length > 0) {
  23668. this.activeCamera = this.cameras[0];
  23669. }
  23670. else {
  23671. this.activeCamera = null;
  23672. }
  23673. }
  23674. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23675. return index;
  23676. };
  23677. Scene.prototype.removeParticleSystem = function (toRemove) {
  23678. var index = this.particleSystems.indexOf(toRemove);
  23679. if (index !== -1) {
  23680. this.particleSystems.splice(index, 1);
  23681. }
  23682. return index;
  23683. };
  23684. ;
  23685. Scene.prototype.removeAnimation = function (toRemove) {
  23686. var index = this.animations.indexOf(toRemove);
  23687. if (index !== -1) {
  23688. this.animations.splice(index, 1);
  23689. }
  23690. return index;
  23691. };
  23692. ;
  23693. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23694. var index = this.multiMaterials.indexOf(toRemove);
  23695. if (index !== -1) {
  23696. this.multiMaterials.splice(index, 1);
  23697. }
  23698. return index;
  23699. };
  23700. ;
  23701. Scene.prototype.removeMaterial = function (toRemove) {
  23702. var index = this.materials.indexOf(toRemove);
  23703. if (index !== -1) {
  23704. this.materials.splice(index, 1);
  23705. }
  23706. return index;
  23707. };
  23708. ;
  23709. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23710. var index = this.lensFlareSystems.indexOf(toRemove);
  23711. if (index !== -1) {
  23712. this.lensFlareSystems.splice(index, 1);
  23713. }
  23714. return index;
  23715. };
  23716. ;
  23717. Scene.prototype.removeActionManager = function (toRemove) {
  23718. var index = this._actionManagers.indexOf(toRemove);
  23719. if (index !== -1) {
  23720. this._actionManagers.splice(index, 1);
  23721. }
  23722. return index;
  23723. };
  23724. ;
  23725. Scene.prototype.addLight = function (newLight) {
  23726. this.lights.push(newLight);
  23727. this.sortLightsByPriority();
  23728. // Add light to all meshes (To support if the light is removed and then readded)
  23729. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23730. var mesh = _a[_i];
  23731. if (mesh._lightSources.indexOf(newLight) === -1) {
  23732. mesh._lightSources.push(newLight);
  23733. mesh._resyncLightSources();
  23734. }
  23735. }
  23736. this.onNewLightAddedObservable.notifyObservers(newLight);
  23737. };
  23738. Scene.prototype.sortLightsByPriority = function () {
  23739. if (this.requireLightSorting) {
  23740. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23741. }
  23742. };
  23743. Scene.prototype.addCamera = function (newCamera) {
  23744. this.cameras.push(newCamera);
  23745. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23746. };
  23747. Scene.prototype.addSkeleton = function (newSkeleton) {
  23748. this.skeletons.push(newSkeleton);
  23749. };
  23750. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23751. this.particleSystems.push(newParticleSystem);
  23752. };
  23753. Scene.prototype.addAnimation = function (newAnimation) {
  23754. this.animations.push(newAnimation);
  23755. };
  23756. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23757. this.multiMaterials.push(newMultiMaterial);
  23758. };
  23759. Scene.prototype.addMaterial = function (newMaterial) {
  23760. this.materials.push(newMaterial);
  23761. };
  23762. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23763. this.morphTargetManagers.push(newMorphTargetManager);
  23764. };
  23765. Scene.prototype.addGeometry = function (newGeometrie) {
  23766. this._geometries.push(newGeometrie);
  23767. };
  23768. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23769. this.lensFlareSystems.push(newLensFlareSystem);
  23770. };
  23771. Scene.prototype.addActionManager = function (newActionManager) {
  23772. this._actionManagers.push(newActionManager);
  23773. };
  23774. /**
  23775. * Switch active camera
  23776. * @param {Camera} newCamera - new active camera
  23777. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23778. */
  23779. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23780. if (attachControl === void 0) { attachControl = true; }
  23781. var canvas = this._engine.getRenderingCanvas();
  23782. if (!canvas) {
  23783. return;
  23784. }
  23785. if (this.activeCamera) {
  23786. this.activeCamera.detachControl(canvas);
  23787. }
  23788. this.activeCamera = newCamera;
  23789. if (attachControl) {
  23790. newCamera.attachControl(canvas);
  23791. }
  23792. };
  23793. /**
  23794. * sets the active camera of the scene using its ID
  23795. * @param {string} id - the camera's ID
  23796. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23797. */
  23798. Scene.prototype.setActiveCameraByID = function (id) {
  23799. var camera = this.getCameraByID(id);
  23800. if (camera) {
  23801. this.activeCamera = camera;
  23802. return camera;
  23803. }
  23804. return null;
  23805. };
  23806. /**
  23807. * sets the active camera of the scene using its name
  23808. * @param {string} name - the camera's name
  23809. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23810. */
  23811. Scene.prototype.setActiveCameraByName = function (name) {
  23812. var camera = this.getCameraByName(name);
  23813. if (camera) {
  23814. this.activeCamera = camera;
  23815. return camera;
  23816. }
  23817. return null;
  23818. };
  23819. /**
  23820. * get an animation group using its name
  23821. * @param {string} the material's name
  23822. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23823. */
  23824. Scene.prototype.getAnimationGroupByName = function (name) {
  23825. for (var index = 0; index < this.animationGroups.length; index++) {
  23826. if (this.animationGroups[index].name === name) {
  23827. return this.animationGroups[index];
  23828. }
  23829. }
  23830. return null;
  23831. };
  23832. /**
  23833. * get a material using its id
  23834. * @param {string} the material's ID
  23835. * @return {BABYLON.Material|null} the material or null if none found.
  23836. */
  23837. Scene.prototype.getMaterialByID = function (id) {
  23838. for (var index = 0; index < this.materials.length; index++) {
  23839. if (this.materials[index].id === id) {
  23840. return this.materials[index];
  23841. }
  23842. }
  23843. return null;
  23844. };
  23845. /**
  23846. * get a material using its name
  23847. * @param {string} the material's name
  23848. * @return {BABYLON.Material|null} the material or null if none found.
  23849. */
  23850. Scene.prototype.getMaterialByName = function (name) {
  23851. for (var index = 0; index < this.materials.length; index++) {
  23852. if (this.materials[index].name === name) {
  23853. return this.materials[index];
  23854. }
  23855. }
  23856. return null;
  23857. };
  23858. Scene.prototype.getLensFlareSystemByName = function (name) {
  23859. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23860. if (this.lensFlareSystems[index].name === name) {
  23861. return this.lensFlareSystems[index];
  23862. }
  23863. }
  23864. return null;
  23865. };
  23866. Scene.prototype.getLensFlareSystemByID = function (id) {
  23867. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23868. if (this.lensFlareSystems[index].id === id) {
  23869. return this.lensFlareSystems[index];
  23870. }
  23871. }
  23872. return null;
  23873. };
  23874. Scene.prototype.getCameraByID = function (id) {
  23875. for (var index = 0; index < this.cameras.length; index++) {
  23876. if (this.cameras[index].id === id) {
  23877. return this.cameras[index];
  23878. }
  23879. }
  23880. return null;
  23881. };
  23882. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23883. for (var index = 0; index < this.cameras.length; index++) {
  23884. if (this.cameras[index].uniqueId === uniqueId) {
  23885. return this.cameras[index];
  23886. }
  23887. }
  23888. return null;
  23889. };
  23890. /**
  23891. * get a camera using its name
  23892. * @param {string} the camera's name
  23893. * @return {BABYLON.Camera|null} the camera or null if none found.
  23894. */
  23895. Scene.prototype.getCameraByName = function (name) {
  23896. for (var index = 0; index < this.cameras.length; index++) {
  23897. if (this.cameras[index].name === name) {
  23898. return this.cameras[index];
  23899. }
  23900. }
  23901. return null;
  23902. };
  23903. /**
  23904. * get a bone using its id
  23905. * @param {string} the bone's id
  23906. * @return {BABYLON.Bone|null} the bone or null if not found
  23907. */
  23908. Scene.prototype.getBoneByID = function (id) {
  23909. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23910. var skeleton = this.skeletons[skeletonIndex];
  23911. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23912. if (skeleton.bones[boneIndex].id === id) {
  23913. return skeleton.bones[boneIndex];
  23914. }
  23915. }
  23916. }
  23917. return null;
  23918. };
  23919. /**
  23920. * get a bone using its id
  23921. * @param {string} the bone's name
  23922. * @return {BABYLON.Bone|null} the bone or null if not found
  23923. */
  23924. Scene.prototype.getBoneByName = function (name) {
  23925. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23926. var skeleton = this.skeletons[skeletonIndex];
  23927. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23928. if (skeleton.bones[boneIndex].name === name) {
  23929. return skeleton.bones[boneIndex];
  23930. }
  23931. }
  23932. }
  23933. return null;
  23934. };
  23935. /**
  23936. * get a light node using its name
  23937. * @param {string} the light's name
  23938. * @return {BABYLON.Light|null} the light or null if none found.
  23939. */
  23940. Scene.prototype.getLightByName = function (name) {
  23941. for (var index = 0; index < this.lights.length; index++) {
  23942. if (this.lights[index].name === name) {
  23943. return this.lights[index];
  23944. }
  23945. }
  23946. return null;
  23947. };
  23948. /**
  23949. * get a light node using its ID
  23950. * @param {string} the light's id
  23951. * @return {BABYLON.Light|null} the light or null if none found.
  23952. */
  23953. Scene.prototype.getLightByID = function (id) {
  23954. for (var index = 0; index < this.lights.length; index++) {
  23955. if (this.lights[index].id === id) {
  23956. return this.lights[index];
  23957. }
  23958. }
  23959. return null;
  23960. };
  23961. /**
  23962. * get a light node using its scene-generated unique ID
  23963. * @param {number} the light's unique id
  23964. * @return {BABYLON.Light|null} the light or null if none found.
  23965. */
  23966. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23967. for (var index = 0; index < this.lights.length; index++) {
  23968. if (this.lights[index].uniqueId === uniqueId) {
  23969. return this.lights[index];
  23970. }
  23971. }
  23972. return null;
  23973. };
  23974. /**
  23975. * get a particle system by id
  23976. * @param id {number} the particle system id
  23977. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23978. */
  23979. Scene.prototype.getParticleSystemByID = function (id) {
  23980. for (var index = 0; index < this.particleSystems.length; index++) {
  23981. if (this.particleSystems[index].id === id) {
  23982. return this.particleSystems[index];
  23983. }
  23984. }
  23985. return null;
  23986. };
  23987. /**
  23988. * get a geometry using its ID
  23989. * @param {string} the geometry's id
  23990. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23991. */
  23992. Scene.prototype.getGeometryByID = function (id) {
  23993. for (var index = 0; index < this._geometries.length; index++) {
  23994. if (this._geometries[index].id === id) {
  23995. return this._geometries[index];
  23996. }
  23997. }
  23998. return null;
  23999. };
  24000. /**
  24001. * add a new geometry to this scene.
  24002. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  24003. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  24004. * @return {boolean} was the geometry added or not
  24005. */
  24006. Scene.prototype.pushGeometry = function (geometry, force) {
  24007. if (!force && this.getGeometryByID(geometry.id)) {
  24008. return false;
  24009. }
  24010. this._geometries.push(geometry);
  24011. //notify the collision coordinator
  24012. if (this.collisionCoordinator) {
  24013. this.collisionCoordinator.onGeometryAdded(geometry);
  24014. }
  24015. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24016. return true;
  24017. };
  24018. /**
  24019. * Removes an existing geometry
  24020. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24021. * @return {boolean} was the geometry removed or not
  24022. */
  24023. Scene.prototype.removeGeometry = function (geometry) {
  24024. var index = this._geometries.indexOf(geometry);
  24025. if (index > -1) {
  24026. this._geometries.splice(index, 1);
  24027. //notify the collision coordinator
  24028. if (this.collisionCoordinator) {
  24029. this.collisionCoordinator.onGeometryDeleted(geometry);
  24030. }
  24031. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24032. return true;
  24033. }
  24034. return false;
  24035. };
  24036. Scene.prototype.getGeometries = function () {
  24037. return this._geometries;
  24038. };
  24039. /**
  24040. * Get the first added mesh found of a given ID
  24041. * @param {string} id - the id to search for
  24042. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24043. */
  24044. Scene.prototype.getMeshByID = function (id) {
  24045. for (var index = 0; index < this.meshes.length; index++) {
  24046. if (this.meshes[index].id === id) {
  24047. return this.meshes[index];
  24048. }
  24049. }
  24050. return null;
  24051. };
  24052. Scene.prototype.getMeshesByID = function (id) {
  24053. return this.meshes.filter(function (m) {
  24054. return m.id === id;
  24055. });
  24056. };
  24057. /**
  24058. * Get the first added transform node found of a given ID
  24059. * @param {string} id - the id to search for
  24060. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24061. */
  24062. Scene.prototype.getTransformNodeByID = function (id) {
  24063. for (var index = 0; index < this.transformNodes.length; index++) {
  24064. if (this.transformNodes[index].id === id) {
  24065. return this.transformNodes[index];
  24066. }
  24067. }
  24068. return null;
  24069. };
  24070. Scene.prototype.getTransformNodesByID = function (id) {
  24071. return this.transformNodes.filter(function (m) {
  24072. return m.id === id;
  24073. });
  24074. };
  24075. /**
  24076. * Get a mesh with its auto-generated unique id
  24077. * @param {number} uniqueId - the unique id to search for
  24078. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24079. */
  24080. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24081. for (var index = 0; index < this.meshes.length; index++) {
  24082. if (this.meshes[index].uniqueId === uniqueId) {
  24083. return this.meshes[index];
  24084. }
  24085. }
  24086. return null;
  24087. };
  24088. /**
  24089. * Get a the last added mesh found of a given ID
  24090. * @param {string} id - the id to search for
  24091. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24092. */
  24093. Scene.prototype.getLastMeshByID = function (id) {
  24094. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24095. if (this.meshes[index].id === id) {
  24096. return this.meshes[index];
  24097. }
  24098. }
  24099. return null;
  24100. };
  24101. /**
  24102. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24103. * @param {string} id - the id to search for
  24104. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24105. */
  24106. Scene.prototype.getLastEntryByID = function (id) {
  24107. var index;
  24108. for (index = this.meshes.length - 1; index >= 0; index--) {
  24109. if (this.meshes[index].id === id) {
  24110. return this.meshes[index];
  24111. }
  24112. }
  24113. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24114. if (this.transformNodes[index].id === id) {
  24115. return this.transformNodes[index];
  24116. }
  24117. }
  24118. for (index = this.cameras.length - 1; index >= 0; index--) {
  24119. if (this.cameras[index].id === id) {
  24120. return this.cameras[index];
  24121. }
  24122. }
  24123. for (index = this.lights.length - 1; index >= 0; index--) {
  24124. if (this.lights[index].id === id) {
  24125. return this.lights[index];
  24126. }
  24127. }
  24128. return null;
  24129. };
  24130. Scene.prototype.getNodeByID = function (id) {
  24131. var mesh = this.getMeshByID(id);
  24132. if (mesh) {
  24133. return mesh;
  24134. }
  24135. var light = this.getLightByID(id);
  24136. if (light) {
  24137. return light;
  24138. }
  24139. var camera = this.getCameraByID(id);
  24140. if (camera) {
  24141. return camera;
  24142. }
  24143. var bone = this.getBoneByID(id);
  24144. return bone;
  24145. };
  24146. Scene.prototype.getNodeByName = function (name) {
  24147. var mesh = this.getMeshByName(name);
  24148. if (mesh) {
  24149. return mesh;
  24150. }
  24151. var light = this.getLightByName(name);
  24152. if (light) {
  24153. return light;
  24154. }
  24155. var camera = this.getCameraByName(name);
  24156. if (camera) {
  24157. return camera;
  24158. }
  24159. var bone = this.getBoneByName(name);
  24160. return bone;
  24161. };
  24162. Scene.prototype.getMeshByName = function (name) {
  24163. for (var index = 0; index < this.meshes.length; index++) {
  24164. if (this.meshes[index].name === name) {
  24165. return this.meshes[index];
  24166. }
  24167. }
  24168. return null;
  24169. };
  24170. Scene.prototype.getTransformNodeByName = function (name) {
  24171. for (var index = 0; index < this.transformNodes.length; index++) {
  24172. if (this.transformNodes[index].name === name) {
  24173. return this.transformNodes[index];
  24174. }
  24175. }
  24176. return null;
  24177. };
  24178. Scene.prototype.getSoundByName = function (name) {
  24179. var index;
  24180. if (BABYLON.AudioEngine) {
  24181. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24182. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24183. return this.mainSoundTrack.soundCollection[index];
  24184. }
  24185. }
  24186. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24187. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24188. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24189. return this.soundTracks[sdIndex].soundCollection[index];
  24190. }
  24191. }
  24192. }
  24193. }
  24194. return null;
  24195. };
  24196. Scene.prototype.getLastSkeletonByID = function (id) {
  24197. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24198. if (this.skeletons[index].id === id) {
  24199. return this.skeletons[index];
  24200. }
  24201. }
  24202. return null;
  24203. };
  24204. Scene.prototype.getSkeletonById = function (id) {
  24205. for (var index = 0; index < this.skeletons.length; index++) {
  24206. if (this.skeletons[index].id === id) {
  24207. return this.skeletons[index];
  24208. }
  24209. }
  24210. return null;
  24211. };
  24212. Scene.prototype.getSkeletonByName = function (name) {
  24213. for (var index = 0; index < this.skeletons.length; index++) {
  24214. if (this.skeletons[index].name === name) {
  24215. return this.skeletons[index];
  24216. }
  24217. }
  24218. return null;
  24219. };
  24220. Scene.prototype.getMorphTargetManagerById = function (id) {
  24221. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24222. if (this.morphTargetManagers[index].uniqueId === id) {
  24223. return this.morphTargetManagers[index];
  24224. }
  24225. }
  24226. return null;
  24227. };
  24228. Scene.prototype.isActiveMesh = function (mesh) {
  24229. return (this._activeMeshes.indexOf(mesh) !== -1);
  24230. };
  24231. /**
  24232. * Return a the first highlight layer of the scene with a given name.
  24233. * @param name The name of the highlight layer to look for.
  24234. * @return The highlight layer if found otherwise null.
  24235. */
  24236. Scene.prototype.getHighlightLayerByName = function (name) {
  24237. for (var index = 0; index < this.effectLayers.length; index++) {
  24238. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24239. return this.effectLayers[index];
  24240. }
  24241. }
  24242. return null;
  24243. };
  24244. /**
  24245. * Return a the first highlight layer of the scene with a given name.
  24246. * @param name The name of the highlight layer to look for.
  24247. * @return The highlight layer if found otherwise null.
  24248. */
  24249. Scene.prototype.getGlowLayerByName = function (name) {
  24250. for (var index = 0; index < this.effectLayers.length; index++) {
  24251. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24252. return this.effectLayers[index];
  24253. }
  24254. }
  24255. return null;
  24256. };
  24257. Object.defineProperty(Scene.prototype, "uid", {
  24258. /**
  24259. * Return a unique id as a string which can serve as an identifier for the scene
  24260. */
  24261. get: function () {
  24262. if (!this._uid) {
  24263. this._uid = BABYLON.Tools.RandomId();
  24264. }
  24265. return this._uid;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. /**
  24271. * Add an externaly attached data from its key.
  24272. * This method call will fail and return false, if such key already exists.
  24273. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24274. * @param key the unique key that identifies the data
  24275. * @param data the data object to associate to the key for this Engine instance
  24276. * @return true if no such key were already present and the data was added successfully, false otherwise
  24277. */
  24278. Scene.prototype.addExternalData = function (key, data) {
  24279. if (!this._externalData) {
  24280. this._externalData = new BABYLON.StringDictionary();
  24281. }
  24282. return this._externalData.add(key, data);
  24283. };
  24284. /**
  24285. * Get an externaly attached data from its key
  24286. * @param key the unique key that identifies the data
  24287. * @return the associated data, if present (can be null), or undefined if not present
  24288. */
  24289. Scene.prototype.getExternalData = function (key) {
  24290. if (!this._externalData) {
  24291. return null;
  24292. }
  24293. return this._externalData.get(key);
  24294. };
  24295. /**
  24296. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24297. * @param key the unique key that identifies the data
  24298. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24299. * @return the associated data, can be null if the factory returned null.
  24300. */
  24301. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24302. if (!this._externalData) {
  24303. this._externalData = new BABYLON.StringDictionary();
  24304. }
  24305. return this._externalData.getOrAddWithFactory(key, factory);
  24306. };
  24307. /**
  24308. * Remove an externaly attached data from the Engine instance
  24309. * @param key the unique key that identifies the data
  24310. * @return true if the data was successfully removed, false if it doesn't exist
  24311. */
  24312. Scene.prototype.removeExternalData = function (key) {
  24313. return this._externalData.remove(key);
  24314. };
  24315. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24316. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24317. if (mesh.showSubMeshesBoundingBox) {
  24318. var boundingInfo = subMesh.getBoundingInfo();
  24319. if (boundingInfo !== null && boundingInfo !== undefined) {
  24320. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24321. }
  24322. }
  24323. var material = subMesh.getMaterial();
  24324. if (material !== null && material !== undefined) {
  24325. // Render targets
  24326. if (material.getRenderTargetTextures !== undefined) {
  24327. if (this._processedMaterials.indexOf(material) === -1) {
  24328. this._processedMaterials.push(material);
  24329. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24330. }
  24331. }
  24332. // Dispatch
  24333. this._activeIndices.addCount(subMesh.indexCount, false);
  24334. this._renderingManager.dispatch(subMesh, mesh, material);
  24335. }
  24336. }
  24337. };
  24338. /**
  24339. * Clear the processed materials smart array preventing retention point in material dispose.
  24340. */
  24341. Scene.prototype.freeProcessedMaterials = function () {
  24342. this._processedMaterials.dispose();
  24343. };
  24344. /**
  24345. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24346. */
  24347. Scene.prototype.freeActiveMeshes = function () {
  24348. this._activeMeshes.dispose();
  24349. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24350. this.activeCamera._activeMeshes.dispose();
  24351. }
  24352. if (this.activeCameras) {
  24353. for (var i = 0; i < this.activeCameras.length; i++) {
  24354. var activeCamera = this.activeCameras[i];
  24355. if (activeCamera && activeCamera._activeMeshes) {
  24356. activeCamera._activeMeshes.dispose();
  24357. }
  24358. }
  24359. }
  24360. };
  24361. /**
  24362. * Clear the info related to rendering groups preventing retention points during dispose.
  24363. */
  24364. Scene.prototype.freeRenderingGroups = function () {
  24365. if (this._renderingManager) {
  24366. this._renderingManager.freeRenderingGroups();
  24367. }
  24368. if (this.textures) {
  24369. for (var i = 0; i < this.textures.length; i++) {
  24370. var texture = this.textures[i];
  24371. if (texture && texture.renderList) {
  24372. texture.freeRenderingGroups();
  24373. }
  24374. }
  24375. }
  24376. };
  24377. Scene.prototype._isInIntermediateRendering = function () {
  24378. return this._intermediateRendering;
  24379. };
  24380. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24381. this._activeMeshCandidateProvider = provider;
  24382. };
  24383. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24384. return this._activeMeshCandidateProvider;
  24385. };
  24386. /**
  24387. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24388. */
  24389. Scene.prototype.freezeActiveMeshes = function () {
  24390. if (!this.activeCamera) {
  24391. return this;
  24392. }
  24393. if (!this._frustumPlanes) {
  24394. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24395. }
  24396. this._evaluateActiveMeshes();
  24397. this._activeMeshesFrozen = true;
  24398. return this;
  24399. };
  24400. /**
  24401. * Use this function to restart evaluating active meshes on every frame
  24402. */
  24403. Scene.prototype.unfreezeActiveMeshes = function () {
  24404. this._activeMeshesFrozen = false;
  24405. return this;
  24406. };
  24407. Scene.prototype._evaluateActiveMeshes = function () {
  24408. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24409. return;
  24410. }
  24411. if (!this.activeCamera) {
  24412. return;
  24413. }
  24414. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24415. this.activeCamera._activeMeshes.reset();
  24416. this._activeMeshes.reset();
  24417. this._renderingManager.reset();
  24418. this._processedMaterials.reset();
  24419. this._activeParticleSystems.reset();
  24420. this._activeSkeletons.reset();
  24421. this._softwareSkinnedMeshes.reset();
  24422. if (this._boundingBoxRenderer) {
  24423. this._boundingBoxRenderer.reset();
  24424. }
  24425. // Meshes
  24426. var meshes;
  24427. var len;
  24428. var checkIsEnabled = true;
  24429. // Determine mesh candidates
  24430. if (this._activeMeshCandidateProvider !== undefined) {
  24431. // Use _activeMeshCandidateProvider
  24432. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24433. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24434. if (meshes !== undefined) {
  24435. len = meshes.length;
  24436. }
  24437. else {
  24438. len = 0;
  24439. }
  24440. }
  24441. else if (this._selectionOctree !== undefined) {
  24442. // Octree
  24443. var selection = this._selectionOctree.select(this._frustumPlanes);
  24444. meshes = selection.data;
  24445. len = selection.length;
  24446. }
  24447. else {
  24448. // Full scene traversal
  24449. len = this.meshes.length;
  24450. meshes = this.meshes;
  24451. }
  24452. // Check each mesh
  24453. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24454. mesh = meshes[meshIndex];
  24455. if (mesh.isBlocked) {
  24456. continue;
  24457. }
  24458. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24459. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24460. continue;
  24461. }
  24462. mesh.computeWorldMatrix();
  24463. // Intersections
  24464. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24465. this._meshesForIntersections.pushNoDuplicate(mesh);
  24466. }
  24467. // Switch to current LOD
  24468. meshLOD = mesh.getLOD(this.activeCamera);
  24469. if (meshLOD === undefined || meshLOD === null) {
  24470. continue;
  24471. }
  24472. mesh._preActivate();
  24473. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24474. this._activeMeshes.push(mesh);
  24475. this.activeCamera._activeMeshes.push(mesh);
  24476. mesh._activate(this._renderId);
  24477. if (meshLOD !== mesh) {
  24478. meshLOD._activate(this._renderId);
  24479. }
  24480. this._activeMesh(mesh, meshLOD);
  24481. }
  24482. }
  24483. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24484. // Particle systems
  24485. if (this.particlesEnabled) {
  24486. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24487. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24488. var particleSystem = this.particleSystems[particleIndex];
  24489. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24490. continue;
  24491. }
  24492. var emitter = particleSystem.emitter;
  24493. if (!emitter.position || emitter.isEnabled()) {
  24494. this._activeParticleSystems.push(particleSystem);
  24495. particleSystem.animate();
  24496. this._renderingManager.dispatchParticles(particleSystem);
  24497. }
  24498. }
  24499. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24500. }
  24501. };
  24502. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24503. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24504. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24505. mesh.skeleton.prepare();
  24506. }
  24507. if (!mesh.computeBonesUsingShaders) {
  24508. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24509. }
  24510. }
  24511. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24512. var boundingInfo = sourceMesh.getBoundingInfo();
  24513. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24514. }
  24515. if (mesh !== undefined && mesh !== null
  24516. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24517. // Submeshes Octrees
  24518. var len;
  24519. var subMeshes;
  24520. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24521. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24522. len = intersections.length;
  24523. subMeshes = intersections.data;
  24524. }
  24525. else {
  24526. subMeshes = mesh.subMeshes;
  24527. len = subMeshes.length;
  24528. }
  24529. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24530. subMesh = subMeshes[subIndex];
  24531. this._evaluateSubMesh(subMesh, mesh);
  24532. }
  24533. }
  24534. };
  24535. Scene.prototype.updateTransformMatrix = function (force) {
  24536. if (!this.activeCamera) {
  24537. return;
  24538. }
  24539. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24540. };
  24541. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24542. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24543. };
  24544. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24545. if (camera && camera._skipRendering) {
  24546. return;
  24547. }
  24548. var engine = this._engine;
  24549. this.activeCamera = camera;
  24550. if (!this.activeCamera)
  24551. throw new Error("Active camera not set");
  24552. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24553. // Viewport
  24554. engine.setViewport(this.activeCamera.viewport);
  24555. // Camera
  24556. this.resetCachedMaterial();
  24557. this._renderId++;
  24558. this.updateTransformMatrix();
  24559. if (camera._alternateCamera) {
  24560. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24561. this._alternateRendering = true;
  24562. }
  24563. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24564. // Meshes
  24565. this._evaluateActiveMeshes();
  24566. // Software skinning
  24567. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24568. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24569. mesh.applySkeleton(mesh.skeleton);
  24570. }
  24571. // Render targets
  24572. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24573. var needsRestoreFrameBuffer = false;
  24574. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24575. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24576. }
  24577. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24578. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24579. }
  24580. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24581. this._intermediateRendering = true;
  24582. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24583. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24584. var renderTarget = this._renderTargets.data[renderIndex];
  24585. if (renderTarget._shouldRender()) {
  24586. this._renderId++;
  24587. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24588. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24589. }
  24590. }
  24591. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24592. this._intermediateRendering = false;
  24593. this._renderId++;
  24594. needsRestoreFrameBuffer = true; // Restore back buffer
  24595. }
  24596. // Render EffecttLayer Texture
  24597. var stencilState = this._engine.getStencilBuffer();
  24598. var renderEffects = false;
  24599. var needStencil = false;
  24600. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24601. this._intermediateRendering = true;
  24602. for (var i = 0; i < this.effectLayers.length; i++) {
  24603. var effectLayer = this.effectLayers[i];
  24604. if (effectLayer.shouldRender() &&
  24605. (!effectLayer.camera ||
  24606. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24607. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24608. renderEffects = true;
  24609. needStencil = needStencil || effectLayer.needStencil();
  24610. var renderTarget = effectLayer._mainTexture;
  24611. if (renderTarget._shouldRender()) {
  24612. this._renderId++;
  24613. renderTarget.render(false, false);
  24614. needsRestoreFrameBuffer = true;
  24615. }
  24616. }
  24617. }
  24618. this._intermediateRendering = false;
  24619. this._renderId++;
  24620. }
  24621. if (needsRestoreFrameBuffer) {
  24622. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24623. }
  24624. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24625. // Prepare Frame
  24626. this.postProcessManager._prepareFrame();
  24627. // Backgrounds
  24628. var layerIndex;
  24629. var layer;
  24630. if (this.layers.length) {
  24631. engine.setDepthBuffer(false);
  24632. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24633. layer = this.layers[layerIndex];
  24634. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24635. layer.render();
  24636. }
  24637. }
  24638. engine.setDepthBuffer(true);
  24639. }
  24640. // Activate effect Layer stencil
  24641. if (needStencil) {
  24642. this._engine.setStencilBuffer(true);
  24643. }
  24644. // Render
  24645. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24646. this._renderingManager.render(null, null, true, true);
  24647. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24648. // Restore effect Layer stencil
  24649. if (needStencil) {
  24650. this._engine.setStencilBuffer(stencilState);
  24651. }
  24652. // Bounding boxes
  24653. if (this._boundingBoxRenderer) {
  24654. this._boundingBoxRenderer.render();
  24655. }
  24656. // Lens flares
  24657. if (this.lensFlaresEnabled) {
  24658. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24659. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24660. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24661. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24662. lensFlareSystem.render();
  24663. }
  24664. }
  24665. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24666. }
  24667. // Foregrounds
  24668. if (this.layers.length) {
  24669. engine.setDepthBuffer(false);
  24670. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24671. layer = this.layers[layerIndex];
  24672. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24673. layer.render();
  24674. }
  24675. }
  24676. engine.setDepthBuffer(true);
  24677. }
  24678. // Effect Layer
  24679. if (renderEffects) {
  24680. engine.setDepthBuffer(false);
  24681. for (var i = 0; i < this.effectLayers.length; i++) {
  24682. if (this.effectLayers[i].shouldRender()) {
  24683. this.effectLayers[i].render();
  24684. }
  24685. }
  24686. engine.setDepthBuffer(true);
  24687. }
  24688. // Finalize frame
  24689. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24690. // Reset some special arrays
  24691. this._renderTargets.reset();
  24692. this._alternateRendering = false;
  24693. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24694. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24695. };
  24696. Scene.prototype._processSubCameras = function (camera) {
  24697. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24698. this._renderForCamera(camera);
  24699. return;
  24700. }
  24701. // rig cameras
  24702. for (var index = 0; index < camera._rigCameras.length; index++) {
  24703. this._renderForCamera(camera._rigCameras[index], camera);
  24704. }
  24705. this.activeCamera = camera;
  24706. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24707. };
  24708. Scene.prototype._checkIntersections = function () {
  24709. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24710. var sourceMesh = this._meshesForIntersections.data[index];
  24711. if (!sourceMesh.actionManager) {
  24712. continue;
  24713. }
  24714. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24715. var action = sourceMesh.actionManager.actions[actionIndex];
  24716. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24717. var parameters = action.getTriggerParameter();
  24718. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24719. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24720. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24721. if (areIntersecting && currentIntersectionInProgress === -1) {
  24722. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24723. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24724. sourceMesh._intersectionsInProgress.push(otherMesh);
  24725. }
  24726. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24727. sourceMesh._intersectionsInProgress.push(otherMesh);
  24728. }
  24729. }
  24730. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24731. //They intersected, and now they don't.
  24732. //is this trigger an exit trigger? execute an event.
  24733. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24734. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24735. }
  24736. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24737. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24738. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24739. }
  24740. }
  24741. }
  24742. }
  24743. }
  24744. };
  24745. Scene.prototype.render = function () {
  24746. if (this.isDisposed) {
  24747. return;
  24748. }
  24749. this._activeParticles.fetchNewFrame();
  24750. this._totalVertices.fetchNewFrame();
  24751. this._activeIndices.fetchNewFrame();
  24752. this._activeBones.fetchNewFrame();
  24753. this._meshesForIntersections.reset();
  24754. this.resetCachedMaterial();
  24755. this.onBeforeAnimationsObservable.notifyObservers(this);
  24756. // Actions
  24757. if (this.actionManager) {
  24758. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24759. }
  24760. //Simplification Queue
  24761. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24762. this.simplificationQueue.executeNext();
  24763. }
  24764. if (this._engine.isDeterministicLockStep()) {
  24765. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24766. var defaultFPS = (60.0 / 1000.0);
  24767. var defaultFrameTime = 1000 / 60; // frame time in MS
  24768. if (this._physicsEngine) {
  24769. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24770. }
  24771. var stepsTaken = 0;
  24772. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24773. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24774. internalSteps = Math.min(internalSteps, maxSubSteps);
  24775. do {
  24776. this.onBeforeStepObservable.notifyObservers(this);
  24777. // Animations
  24778. this._animationRatio = defaultFrameTime * defaultFPS;
  24779. this._animate();
  24780. this.onAfterAnimationsObservable.notifyObservers(this);
  24781. // Physics
  24782. if (this._physicsEngine) {
  24783. this.onBeforePhysicsObservable.notifyObservers(this);
  24784. this._physicsEngine._step(defaultFrameTime / 1000);
  24785. this.onAfterPhysicsObservable.notifyObservers(this);
  24786. }
  24787. this.onAfterStepObservable.notifyObservers(this);
  24788. this._currentStepId++;
  24789. stepsTaken++;
  24790. deltaTime -= defaultFrameTime;
  24791. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24792. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24793. }
  24794. else {
  24795. // Animations
  24796. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24797. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24798. this._animate();
  24799. this.onAfterAnimationsObservable.notifyObservers(this);
  24800. // Physics
  24801. if (this._physicsEngine) {
  24802. this.onBeforePhysicsObservable.notifyObservers(this);
  24803. this._physicsEngine._step(deltaTime / 1000.0);
  24804. this.onAfterPhysicsObservable.notifyObservers(this);
  24805. }
  24806. }
  24807. // update gamepad manager
  24808. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24809. this._gamepadManager._checkGamepadsStatus();
  24810. }
  24811. // Update Cameras
  24812. if (this.activeCameras.length > 0) {
  24813. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24814. var camera = this.activeCameras[cameraIndex];
  24815. camera.update();
  24816. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24817. // rig cameras
  24818. for (var index = 0; index < camera._rigCameras.length; index++) {
  24819. camera._rigCameras[index].update();
  24820. }
  24821. }
  24822. }
  24823. }
  24824. else if (this.activeCamera) {
  24825. this.activeCamera.update();
  24826. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24827. // rig cameras
  24828. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24829. this.activeCamera._rigCameras[index].update();
  24830. }
  24831. }
  24832. }
  24833. // Before render
  24834. this.onBeforeRenderObservable.notifyObservers(this);
  24835. // Customs render targets
  24836. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24837. var engine = this.getEngine();
  24838. var currentActiveCamera = this.activeCamera;
  24839. if (this.renderTargetsEnabled) {
  24840. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24841. this._intermediateRendering = true;
  24842. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24843. var renderTarget = this.customRenderTargets[customIndex];
  24844. if (renderTarget._shouldRender()) {
  24845. this._renderId++;
  24846. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24847. if (!this.activeCamera)
  24848. throw new Error("Active camera not set");
  24849. // Viewport
  24850. engine.setViewport(this.activeCamera.viewport);
  24851. // Camera
  24852. this.updateTransformMatrix();
  24853. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24854. }
  24855. }
  24856. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24857. this._intermediateRendering = false;
  24858. this._renderId++;
  24859. }
  24860. // Restore back buffer
  24861. if (this.customRenderTargets.length > 0) {
  24862. engine.restoreDefaultFramebuffer();
  24863. }
  24864. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24865. this.activeCamera = currentActiveCamera;
  24866. // Procedural textures
  24867. if (this.proceduralTexturesEnabled) {
  24868. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24869. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24870. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24871. if (proceduralTexture._shouldRender()) {
  24872. proceduralTexture.render();
  24873. }
  24874. }
  24875. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24876. }
  24877. // Clear
  24878. if (this.autoClearDepthAndStencil || this.autoClear) {
  24879. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24880. }
  24881. // Shadows
  24882. if (this.shadowsEnabled) {
  24883. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24884. var light = this.lights[lightIndex];
  24885. var shadowGenerator = light.getShadowGenerator();
  24886. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24887. var shadowMap = (shadowGenerator.getShadowMap());
  24888. if (this.textures.indexOf(shadowMap) !== -1) {
  24889. this._renderTargets.push(shadowMap);
  24890. }
  24891. }
  24892. }
  24893. }
  24894. // Depth renderer
  24895. for (var key in this._depthRenderer) {
  24896. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24897. }
  24898. // Geometry renderer
  24899. if (this._geometryBufferRenderer) {
  24900. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24901. }
  24902. // RenderPipeline
  24903. if (this._postProcessRenderPipelineManager) {
  24904. this._postProcessRenderPipelineManager.update();
  24905. }
  24906. // Multi-cameras?
  24907. if (this.activeCameras.length > 0) {
  24908. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24909. if (cameraIndex > 0) {
  24910. this._engine.clear(null, false, true, true);
  24911. }
  24912. this._processSubCameras(this.activeCameras[cameraIndex]);
  24913. }
  24914. }
  24915. else {
  24916. if (!this.activeCamera) {
  24917. throw new Error("No camera defined");
  24918. }
  24919. this._processSubCameras(this.activeCamera);
  24920. }
  24921. // Intersection checks
  24922. this._checkIntersections();
  24923. // Update the audio listener attached to the camera
  24924. if (BABYLON.AudioEngine) {
  24925. this._updateAudioParameters();
  24926. }
  24927. // After render
  24928. if (this.afterRender) {
  24929. this.afterRender();
  24930. }
  24931. this.onAfterRenderObservable.notifyObservers(this);
  24932. // Cleaning
  24933. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24934. var data = this._toBeDisposed.data[index];
  24935. if (data) {
  24936. data.dispose();
  24937. }
  24938. this._toBeDisposed[index] = null;
  24939. }
  24940. this._toBeDisposed.reset();
  24941. if (this.dumpNextRenderTargets) {
  24942. this.dumpNextRenderTargets = false;
  24943. }
  24944. this._activeBones.addCount(0, true);
  24945. this._activeIndices.addCount(0, true);
  24946. this._activeParticles.addCount(0, true);
  24947. };
  24948. Scene.prototype._updateAudioParameters = function () {
  24949. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24950. return;
  24951. }
  24952. var listeningCamera;
  24953. var audioEngine = BABYLON.Engine.audioEngine;
  24954. if (this.activeCameras.length > 0) {
  24955. listeningCamera = this.activeCameras[0];
  24956. }
  24957. else {
  24958. listeningCamera = this.activeCamera;
  24959. }
  24960. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24961. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24962. // for VR cameras
  24963. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24964. listeningCamera = listeningCamera.rigCameras[0];
  24965. }
  24966. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24967. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24968. cameraDirection.normalize();
  24969. // To avoid some errors on GearVR
  24970. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24971. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24972. }
  24973. var i;
  24974. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24975. var sound = this.mainSoundTrack.soundCollection[i];
  24976. if (sound.useCustomAttenuation) {
  24977. sound.updateDistanceFromListener();
  24978. }
  24979. }
  24980. for (i = 0; i < this.soundTracks.length; i++) {
  24981. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24982. sound = this.soundTracks[i].soundCollection[j];
  24983. if (sound.useCustomAttenuation) {
  24984. sound.updateDistanceFromListener();
  24985. }
  24986. }
  24987. }
  24988. }
  24989. };
  24990. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24991. // Audio
  24992. get: function () {
  24993. return this._audioEnabled;
  24994. },
  24995. set: function (value) {
  24996. this._audioEnabled = value;
  24997. if (BABYLON.AudioEngine) {
  24998. if (this._audioEnabled) {
  24999. this._enableAudio();
  25000. }
  25001. else {
  25002. this._disableAudio();
  25003. }
  25004. }
  25005. },
  25006. enumerable: true,
  25007. configurable: true
  25008. });
  25009. Scene.prototype._disableAudio = function () {
  25010. var i;
  25011. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25012. this.mainSoundTrack.soundCollection[i].pause();
  25013. }
  25014. for (i = 0; i < this.soundTracks.length; i++) {
  25015. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25016. this.soundTracks[i].soundCollection[j].pause();
  25017. }
  25018. }
  25019. };
  25020. Scene.prototype._enableAudio = function () {
  25021. var i;
  25022. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25023. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25024. this.mainSoundTrack.soundCollection[i].play();
  25025. }
  25026. }
  25027. for (i = 0; i < this.soundTracks.length; i++) {
  25028. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25029. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25030. this.soundTracks[i].soundCollection[j].play();
  25031. }
  25032. }
  25033. }
  25034. };
  25035. Object.defineProperty(Scene.prototype, "headphone", {
  25036. get: function () {
  25037. return this._headphone;
  25038. },
  25039. set: function (value) {
  25040. this._headphone = value;
  25041. if (BABYLON.AudioEngine) {
  25042. if (this._headphone) {
  25043. this._switchAudioModeForHeadphones();
  25044. }
  25045. else {
  25046. this._switchAudioModeForNormalSpeakers();
  25047. }
  25048. }
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. Scene.prototype._switchAudioModeForHeadphones = function () {
  25054. this.mainSoundTrack.switchPanningModelToHRTF();
  25055. for (var i = 0; i < this.soundTracks.length; i++) {
  25056. this.soundTracks[i].switchPanningModelToHRTF();
  25057. }
  25058. };
  25059. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25060. this.mainSoundTrack.switchPanningModelToEqualPower();
  25061. for (var i = 0; i < this.soundTracks.length; i++) {
  25062. this.soundTracks[i].switchPanningModelToEqualPower();
  25063. }
  25064. };
  25065. /**
  25066. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25067. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25068. * @returns the created depth renderer
  25069. */
  25070. Scene.prototype.enableDepthRenderer = function (camera) {
  25071. camera = camera || this.activeCamera;
  25072. if (!camera) {
  25073. throw "No camera available to enable depth renderer";
  25074. }
  25075. if (!this._depthRenderer[camera.id]) {
  25076. var textureType = 0;
  25077. if (this._engine.getCaps().textureHalfFloatRender) {
  25078. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  25079. }
  25080. else if (this._engine.getCaps().textureFloatRender) {
  25081. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  25082. }
  25083. else {
  25084. throw "Depth renderer does not support int texture type";
  25085. }
  25086. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  25087. }
  25088. return this._depthRenderer[camera.id];
  25089. };
  25090. /**
  25091. * Disables a depth renderer for a given camera
  25092. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25093. */
  25094. Scene.prototype.disableDepthRenderer = function (camera) {
  25095. camera = camera || this.activeCamera;
  25096. if (!camera || !this._depthRenderer[camera.id]) {
  25097. return;
  25098. }
  25099. this._depthRenderer[camera.id].dispose();
  25100. delete this._depthRenderer[camera.id];
  25101. };
  25102. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25103. if (ratio === void 0) { ratio = 1; }
  25104. if (this._geometryBufferRenderer) {
  25105. return this._geometryBufferRenderer;
  25106. }
  25107. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25108. if (!this._geometryBufferRenderer.isSupported) {
  25109. this._geometryBufferRenderer = null;
  25110. }
  25111. return this._geometryBufferRenderer;
  25112. };
  25113. Scene.prototype.disableGeometryBufferRenderer = function () {
  25114. if (!this._geometryBufferRenderer) {
  25115. return;
  25116. }
  25117. this._geometryBufferRenderer.dispose();
  25118. this._geometryBufferRenderer = null;
  25119. };
  25120. Scene.prototype.freezeMaterials = function () {
  25121. for (var i = 0; i < this.materials.length; i++) {
  25122. this.materials[i].freeze();
  25123. }
  25124. };
  25125. Scene.prototype.unfreezeMaterials = function () {
  25126. for (var i = 0; i < this.materials.length; i++) {
  25127. this.materials[i].unfreeze();
  25128. }
  25129. };
  25130. Scene.prototype.dispose = function () {
  25131. this.beforeRender = null;
  25132. this.afterRender = null;
  25133. this.skeletons = [];
  25134. this.morphTargetManagers = [];
  25135. this.importedMeshesFiles = new Array();
  25136. this.stopAllAnimations();
  25137. this.resetCachedMaterial();
  25138. for (var key in this._depthRenderer) {
  25139. this._depthRenderer[key].dispose();
  25140. }
  25141. if (this._gamepadManager) {
  25142. this._gamepadManager.dispose();
  25143. this._gamepadManager = null;
  25144. }
  25145. // Smart arrays
  25146. if (this.activeCamera) {
  25147. this.activeCamera._activeMeshes.dispose();
  25148. this.activeCamera = null;
  25149. }
  25150. this._activeMeshes.dispose();
  25151. this._renderingManager.dispose();
  25152. this._processedMaterials.dispose();
  25153. this._activeParticleSystems.dispose();
  25154. this._activeSkeletons.dispose();
  25155. this._softwareSkinnedMeshes.dispose();
  25156. this._renderTargets.dispose();
  25157. this._registeredForLateAnimationBindings.dispose();
  25158. if (this._boundingBoxRenderer) {
  25159. this._boundingBoxRenderer.dispose();
  25160. }
  25161. this._meshesForIntersections.dispose();
  25162. this._toBeDisposed.dispose();
  25163. // Abort active requests
  25164. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25165. var request = _a[_i];
  25166. request.abort();
  25167. }
  25168. // Debug layer
  25169. if (this._debugLayer) {
  25170. this._debugLayer.hide();
  25171. }
  25172. // Events
  25173. this.onDisposeObservable.notifyObservers(this);
  25174. this.onDisposeObservable.clear();
  25175. this.onBeforeRenderObservable.clear();
  25176. this.onAfterRenderObservable.clear();
  25177. this.OnBeforeRenderTargetsRenderObservable.clear();
  25178. this.OnAfterRenderTargetsRenderObservable.clear();
  25179. this.onAfterStepObservable.clear();
  25180. this.onBeforeStepObservable.clear();
  25181. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25182. this.onAfterActiveMeshesEvaluationObservable.clear();
  25183. this.onBeforeParticlesRenderingObservable.clear();
  25184. this.onAfterParticlesRenderingObservable.clear();
  25185. this.onBeforeSpritesRenderingObservable.clear();
  25186. this.onAfterSpritesRenderingObservable.clear();
  25187. this.onBeforeDrawPhaseObservable.clear();
  25188. this.onAfterDrawPhaseObservable.clear();
  25189. this.onBeforePhysicsObservable.clear();
  25190. this.onAfterPhysicsObservable.clear();
  25191. this.onBeforeAnimationsObservable.clear();
  25192. this.onAfterAnimationsObservable.clear();
  25193. this.onDataLoadedObservable.clear();
  25194. this.detachControl();
  25195. // Release sounds & sounds tracks
  25196. if (BABYLON.AudioEngine) {
  25197. this.disposeSounds();
  25198. }
  25199. // VR Helper
  25200. if (this.VRHelper) {
  25201. this.VRHelper.dispose();
  25202. }
  25203. // Detach cameras
  25204. var canvas = this._engine.getRenderingCanvas();
  25205. if (canvas) {
  25206. var index;
  25207. for (index = 0; index < this.cameras.length; index++) {
  25208. this.cameras[index].detachControl(canvas);
  25209. }
  25210. }
  25211. // Release animation groups
  25212. while (this.animationGroups.length) {
  25213. this.animationGroups[0].dispose();
  25214. }
  25215. // Release lights
  25216. while (this.lights.length) {
  25217. this.lights[0].dispose();
  25218. }
  25219. // Release meshes
  25220. while (this.meshes.length) {
  25221. this.meshes[0].dispose(true);
  25222. }
  25223. while (this.transformNodes.length) {
  25224. this.removeTransformNode(this.transformNodes[0]);
  25225. }
  25226. // Release cameras
  25227. while (this.cameras.length) {
  25228. this.cameras[0].dispose();
  25229. }
  25230. // Release materials
  25231. if (this.defaultMaterial) {
  25232. this.defaultMaterial.dispose();
  25233. }
  25234. while (this.multiMaterials.length) {
  25235. this.multiMaterials[0].dispose();
  25236. }
  25237. while (this.materials.length) {
  25238. this.materials[0].dispose();
  25239. }
  25240. // Release particles
  25241. while (this.particleSystems.length) {
  25242. this.particleSystems[0].dispose();
  25243. }
  25244. // Release sprites
  25245. while (this.spriteManagers.length) {
  25246. this.spriteManagers[0].dispose();
  25247. }
  25248. // Release postProcesses
  25249. while (this.postProcesses.length) {
  25250. this.postProcesses[0].dispose();
  25251. }
  25252. // Release layers
  25253. while (this.layers.length) {
  25254. this.layers[0].dispose();
  25255. }
  25256. while (this.effectLayers.length) {
  25257. this.effectLayers[0].dispose();
  25258. }
  25259. // Release textures
  25260. while (this.textures.length) {
  25261. this.textures[0].dispose();
  25262. }
  25263. // Release UBO
  25264. this._sceneUbo.dispose();
  25265. if (this._alternateSceneUbo) {
  25266. this._alternateSceneUbo.dispose();
  25267. }
  25268. // Post-processes
  25269. this.postProcessManager.dispose();
  25270. if (this._postProcessRenderPipelineManager) {
  25271. this._postProcessRenderPipelineManager.dispose();
  25272. }
  25273. // Physics
  25274. if (this._physicsEngine) {
  25275. this.disablePhysicsEngine();
  25276. }
  25277. // Remove from engine
  25278. index = this._engine.scenes.indexOf(this);
  25279. if (index > -1) {
  25280. this._engine.scenes.splice(index, 1);
  25281. }
  25282. this._engine.wipeCaches(true);
  25283. this._isDisposed = true;
  25284. };
  25285. Object.defineProperty(Scene.prototype, "isDisposed", {
  25286. get: function () {
  25287. return this._isDisposed;
  25288. },
  25289. enumerable: true,
  25290. configurable: true
  25291. });
  25292. // Release sounds & sounds tracks
  25293. Scene.prototype.disposeSounds = function () {
  25294. if (!this._mainSoundTrack) {
  25295. return;
  25296. }
  25297. this.mainSoundTrack.dispose();
  25298. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25299. this.soundTracks[scIndex].dispose();
  25300. }
  25301. };
  25302. // Octrees
  25303. /**
  25304. * Get the world extend vectors with an optional filter
  25305. *
  25306. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25307. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25308. */
  25309. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25310. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25311. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25312. filterPredicate = filterPredicate || (function () { return true; });
  25313. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25314. mesh.computeWorldMatrix(true);
  25315. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25316. return;
  25317. }
  25318. var boundingInfo = mesh.getBoundingInfo();
  25319. var minBox = boundingInfo.boundingBox.minimumWorld;
  25320. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25321. BABYLON.Tools.CheckExtends(minBox, min, max);
  25322. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25323. });
  25324. return {
  25325. min: min,
  25326. max: max
  25327. };
  25328. };
  25329. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25330. if (maxCapacity === void 0) { maxCapacity = 64; }
  25331. if (maxDepth === void 0) { maxDepth = 2; }
  25332. if (!this._selectionOctree) {
  25333. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25334. }
  25335. var worldExtends = this.getWorldExtends();
  25336. // Update octree
  25337. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25338. return this._selectionOctree;
  25339. };
  25340. // Picking
  25341. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25342. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25343. var result = BABYLON.Ray.Zero();
  25344. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25345. return result;
  25346. };
  25347. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25348. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25349. var engine = this._engine;
  25350. if (!camera) {
  25351. if (!this.activeCamera)
  25352. throw new Error("Active camera not set");
  25353. camera = this.activeCamera;
  25354. }
  25355. var cameraViewport = camera.viewport;
  25356. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25357. // Moving coordinates to local viewport world
  25358. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25359. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25360. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25361. return this;
  25362. };
  25363. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25364. var result = BABYLON.Ray.Zero();
  25365. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25366. return result;
  25367. };
  25368. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25369. if (!BABYLON.PickingInfo) {
  25370. return this;
  25371. }
  25372. var engine = this._engine;
  25373. if (!camera) {
  25374. if (!this.activeCamera)
  25375. throw new Error("Active camera not set");
  25376. camera = this.activeCamera;
  25377. }
  25378. var cameraViewport = camera.viewport;
  25379. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25380. var identity = BABYLON.Matrix.Identity();
  25381. // Moving coordinates to local viewport world
  25382. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25383. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25384. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25385. return this;
  25386. };
  25387. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25388. if (!BABYLON.PickingInfo) {
  25389. return null;
  25390. }
  25391. var pickingInfo = null;
  25392. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25393. var mesh = this.meshes[meshIndex];
  25394. if (predicate) {
  25395. if (!predicate(mesh)) {
  25396. continue;
  25397. }
  25398. }
  25399. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25400. continue;
  25401. }
  25402. var world = mesh.getWorldMatrix();
  25403. var ray = rayFunction(world);
  25404. var result = mesh.intersects(ray, fastCheck);
  25405. if (!result || !result.hit)
  25406. continue;
  25407. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25408. continue;
  25409. pickingInfo = result;
  25410. if (fastCheck) {
  25411. break;
  25412. }
  25413. }
  25414. return pickingInfo || new BABYLON.PickingInfo();
  25415. };
  25416. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25417. if (!BABYLON.PickingInfo) {
  25418. return null;
  25419. }
  25420. var pickingInfos = new Array();
  25421. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25422. var mesh = this.meshes[meshIndex];
  25423. if (predicate) {
  25424. if (!predicate(mesh)) {
  25425. continue;
  25426. }
  25427. }
  25428. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25429. continue;
  25430. }
  25431. var world = mesh.getWorldMatrix();
  25432. var ray = rayFunction(world);
  25433. var result = mesh.intersects(ray, false);
  25434. if (!result || !result.hit)
  25435. continue;
  25436. pickingInfos.push(result);
  25437. }
  25438. return pickingInfos;
  25439. };
  25440. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25441. if (!BABYLON.PickingInfo) {
  25442. return null;
  25443. }
  25444. var pickingInfo = null;
  25445. if (!camera) {
  25446. if (!this.activeCamera) {
  25447. return null;
  25448. }
  25449. camera = this.activeCamera;
  25450. }
  25451. if (this.spriteManagers.length > 0) {
  25452. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25453. var spriteManager = this.spriteManagers[spriteIndex];
  25454. if (!spriteManager.isPickable) {
  25455. continue;
  25456. }
  25457. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25458. if (!result || !result.hit)
  25459. continue;
  25460. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25461. continue;
  25462. pickingInfo = result;
  25463. if (fastCheck) {
  25464. break;
  25465. }
  25466. }
  25467. }
  25468. return pickingInfo || new BABYLON.PickingInfo();
  25469. };
  25470. /** Launch a ray to try to pick a mesh in the scene
  25471. * @param x position on screen
  25472. * @param y position on screen
  25473. * @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
  25474. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25475. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25476. */
  25477. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25478. var _this = this;
  25479. if (!BABYLON.PickingInfo) {
  25480. return null;
  25481. }
  25482. return this._internalPick(function (world) {
  25483. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25484. return _this._tempPickingRay;
  25485. }, predicate, fastCheck);
  25486. };
  25487. /** Launch a ray to try to pick a sprite in the scene
  25488. * @param x position on screen
  25489. * @param y position on screen
  25490. * @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
  25491. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25492. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25493. */
  25494. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25495. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25496. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25497. };
  25498. /** Use the given ray to pick a mesh in the scene
  25499. * @param ray The ray to use to pick meshes
  25500. * @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
  25501. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25502. */
  25503. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25504. var _this = this;
  25505. return this._internalPick(function (world) {
  25506. if (!_this._pickWithRayInverseMatrix) {
  25507. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25508. }
  25509. world.invertToRef(_this._pickWithRayInverseMatrix);
  25510. if (!_this._cachedRayForTransform) {
  25511. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25512. }
  25513. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25514. return _this._cachedRayForTransform;
  25515. }, predicate, fastCheck);
  25516. };
  25517. /**
  25518. * Launch a ray to try to pick a mesh in the scene
  25519. * @param x X position on screen
  25520. * @param y Y position on screen
  25521. * @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
  25522. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25523. */
  25524. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25525. var _this = this;
  25526. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25527. };
  25528. /**
  25529. * Launch a ray to try to pick a mesh in the scene
  25530. * @param ray Ray to use
  25531. * @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
  25532. */
  25533. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25534. var _this = this;
  25535. return this._internalMultiPick(function (world) {
  25536. if (!_this._pickWithRayInverseMatrix) {
  25537. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25538. }
  25539. world.invertToRef(_this._pickWithRayInverseMatrix);
  25540. if (!_this._cachedRayForTransform) {
  25541. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25542. }
  25543. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25544. return _this._cachedRayForTransform;
  25545. }, predicate);
  25546. };
  25547. Scene.prototype.setPointerOverMesh = function (mesh) {
  25548. if (this._pointerOverMesh === mesh) {
  25549. return;
  25550. }
  25551. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25552. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25553. }
  25554. this._pointerOverMesh = mesh;
  25555. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25556. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25557. }
  25558. };
  25559. Scene.prototype.getPointerOverMesh = function () {
  25560. return this._pointerOverMesh;
  25561. };
  25562. Scene.prototype.setPointerOverSprite = function (sprite) {
  25563. if (this._pointerOverSprite === sprite) {
  25564. return;
  25565. }
  25566. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25567. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25568. }
  25569. this._pointerOverSprite = sprite;
  25570. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25571. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25572. }
  25573. };
  25574. Scene.prototype.getPointerOverSprite = function () {
  25575. return this._pointerOverSprite;
  25576. };
  25577. // Physics
  25578. Scene.prototype.getPhysicsEngine = function () {
  25579. return this._physicsEngine;
  25580. };
  25581. /**
  25582. * Enables physics to the current scene
  25583. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25584. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25585. * @return {boolean} was the physics engine initialized
  25586. */
  25587. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25588. if (gravity === void 0) { gravity = null; }
  25589. if (this._physicsEngine) {
  25590. return true;
  25591. }
  25592. try {
  25593. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25594. return true;
  25595. }
  25596. catch (e) {
  25597. BABYLON.Tools.Error(e.message);
  25598. return false;
  25599. }
  25600. };
  25601. Scene.prototype.disablePhysicsEngine = function () {
  25602. if (!this._physicsEngine) {
  25603. return;
  25604. }
  25605. this._physicsEngine.dispose();
  25606. this._physicsEngine = null;
  25607. };
  25608. Scene.prototype.isPhysicsEnabled = function () {
  25609. return this._physicsEngine !== undefined;
  25610. };
  25611. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25612. var mesh = compound.parts[0].mesh;
  25613. if (mesh.physicsImpostor) {
  25614. mesh.physicsImpostor.dispose();
  25615. mesh.physicsImpostor = null;
  25616. }
  25617. };
  25618. // Misc.
  25619. Scene.prototype._rebuildGeometries = function () {
  25620. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25621. var geometry = _a[_i];
  25622. geometry._rebuild();
  25623. }
  25624. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25625. var mesh = _c[_b];
  25626. mesh._rebuild();
  25627. }
  25628. if (this.postProcessManager) {
  25629. this.postProcessManager._rebuild();
  25630. }
  25631. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25632. var layer = _e[_d];
  25633. layer._rebuild();
  25634. }
  25635. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25636. var effectLayer = _g[_f];
  25637. effectLayer._rebuild();
  25638. }
  25639. if (this._boundingBoxRenderer) {
  25640. this._boundingBoxRenderer._rebuild();
  25641. }
  25642. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25643. var system = _j[_h];
  25644. system.rebuild();
  25645. }
  25646. if (this._postProcessRenderPipelineManager) {
  25647. this._postProcessRenderPipelineManager._rebuild();
  25648. }
  25649. };
  25650. Scene.prototype._rebuildTextures = function () {
  25651. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25652. var texture = _a[_i];
  25653. texture._rebuild();
  25654. }
  25655. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25656. };
  25657. /**
  25658. * Creates a default light for the scene.
  25659. * @param replace Whether to replace the existing lights in the scene.
  25660. */
  25661. Scene.prototype.createDefaultLight = function (replace) {
  25662. if (replace === void 0) { replace = false; }
  25663. // Dispose existing light in replace mode.
  25664. if (replace) {
  25665. if (this.lights) {
  25666. for (var i = 0; i < this.lights.length; i++) {
  25667. this.lights[i].dispose();
  25668. }
  25669. }
  25670. }
  25671. // Light
  25672. if (this.lights.length === 0) {
  25673. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25674. }
  25675. };
  25676. /**
  25677. * Creates a default camera for the scene.
  25678. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25679. * @param replace Whether to replace the existing active camera in the scene.
  25680. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25681. */
  25682. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25683. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25684. if (replace === void 0) { replace = false; }
  25685. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25686. // Dispose existing camera in replace mode.
  25687. if (replace) {
  25688. if (this.activeCamera) {
  25689. this.activeCamera.dispose();
  25690. this.activeCamera = null;
  25691. }
  25692. }
  25693. // Camera
  25694. if (!this.activeCamera) {
  25695. var worldExtends = this.getWorldExtends();
  25696. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25697. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25698. var camera;
  25699. var radius = worldSize.length() * 1.5;
  25700. // empty scene scenario!
  25701. if (!isFinite(radius)) {
  25702. radius = 1;
  25703. worldCenter.copyFromFloats(0, 0, 0);
  25704. }
  25705. if (createArcRotateCamera) {
  25706. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25707. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25708. arcRotateCamera.wheelPrecision = 100 / radius;
  25709. camera = arcRotateCamera;
  25710. }
  25711. else {
  25712. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25713. freeCamera.setTarget(worldCenter);
  25714. camera = freeCamera;
  25715. }
  25716. camera.minZ = radius * 0.01;
  25717. camera.maxZ = radius * 1000;
  25718. camera.speed = radius * 0.2;
  25719. this.activeCamera = camera;
  25720. var canvas = this.getEngine().getRenderingCanvas();
  25721. if (attachCameraControls && canvas) {
  25722. camera.attachControl(canvas);
  25723. }
  25724. }
  25725. };
  25726. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25727. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25728. if (replace === void 0) { replace = false; }
  25729. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25730. this.createDefaultLight(replace);
  25731. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25732. };
  25733. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25734. if (pbr === void 0) { pbr = false; }
  25735. if (scale === void 0) { scale = 1000; }
  25736. if (blur === void 0) { blur = 0; }
  25737. if (environmentTexture) {
  25738. this.environmentTexture = environmentTexture;
  25739. }
  25740. if (!this.environmentTexture) {
  25741. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25742. return null;
  25743. }
  25744. // Skybox
  25745. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25746. if (pbr) {
  25747. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25748. hdrSkyboxMaterial.backFaceCulling = false;
  25749. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25750. if (hdrSkyboxMaterial.reflectionTexture) {
  25751. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25752. }
  25753. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25754. hdrSkyboxMaterial.disableLighting = true;
  25755. hdrSkyboxMaterial.twoSidedLighting = true;
  25756. hdrSkybox.infiniteDistance = true;
  25757. hdrSkybox.material = hdrSkyboxMaterial;
  25758. }
  25759. else {
  25760. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25761. skyboxMaterial.backFaceCulling = false;
  25762. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25763. if (skyboxMaterial.reflectionTexture) {
  25764. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25765. }
  25766. skyboxMaterial.disableLighting = true;
  25767. hdrSkybox.infiniteDistance = true;
  25768. hdrSkybox.material = skyboxMaterial;
  25769. }
  25770. return hdrSkybox;
  25771. };
  25772. Scene.prototype.createDefaultEnvironment = function (options) {
  25773. if (BABYLON.EnvironmentHelper) {
  25774. return new BABYLON.EnvironmentHelper(options, this);
  25775. }
  25776. return null;
  25777. };
  25778. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25779. if (webVROptions === void 0) { webVROptions = {}; }
  25780. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25781. };
  25782. // Tags
  25783. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25784. if (tagsQuery === undefined) {
  25785. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25786. return list;
  25787. }
  25788. var listByTags = [];
  25789. forEach = forEach || (function (item) { return; });
  25790. for (var i in list) {
  25791. var item = list[i];
  25792. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25793. listByTags.push(item);
  25794. forEach(item);
  25795. }
  25796. }
  25797. return listByTags;
  25798. };
  25799. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25800. return this._getByTags(this.meshes, tagsQuery, forEach);
  25801. };
  25802. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25803. return this._getByTags(this.cameras, tagsQuery, forEach);
  25804. };
  25805. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25806. return this._getByTags(this.lights, tagsQuery, forEach);
  25807. };
  25808. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25809. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25810. };
  25811. /**
  25812. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25813. * This allowed control for front to back rendering or reversly depending of the special needs.
  25814. *
  25815. * @param renderingGroupId The rendering group id corresponding to its index
  25816. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25817. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25818. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25819. */
  25820. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25821. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25822. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25823. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25824. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25825. };
  25826. /**
  25827. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25828. *
  25829. * @param renderingGroupId The rendering group id corresponding to its index
  25830. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25831. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25832. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25833. */
  25834. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25835. if (depth === void 0) { depth = true; }
  25836. if (stencil === void 0) { stencil = true; }
  25837. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25838. };
  25839. /**
  25840. * Will flag all materials as dirty to trigger new shader compilation
  25841. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25842. */
  25843. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25844. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25845. var material = _a[_i];
  25846. if (predicate && !predicate(material)) {
  25847. continue;
  25848. }
  25849. material.markAsDirty(flag);
  25850. }
  25851. };
  25852. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25853. var _this = this;
  25854. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25855. this._activeRequests.push(request);
  25856. request.onCompleteObservable.add(function (request) {
  25857. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25858. });
  25859. return request;
  25860. };
  25861. /** @ignore */
  25862. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25863. var _this = this;
  25864. return new Promise(function (resolve, reject) {
  25865. _this._loadFile(url, function (data) {
  25866. resolve(data);
  25867. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25868. reject(exception);
  25869. });
  25870. });
  25871. };
  25872. // Statics
  25873. Scene._FOGMODE_NONE = 0;
  25874. Scene._FOGMODE_EXP = 1;
  25875. Scene._FOGMODE_EXP2 = 2;
  25876. Scene._FOGMODE_LINEAR = 3;
  25877. Scene._uniqueIdCounter = 0;
  25878. Scene.MinDeltaTime = 1.0;
  25879. Scene.MaxDeltaTime = 1000.0;
  25880. /** The distance in pixel that you have to move to prevent some events */
  25881. Scene.DragMovementThreshold = 10; // in pixels
  25882. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25883. Scene.LongPressDelay = 500; // in milliseconds
  25884. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25885. Scene.DoubleClickDelay = 300; // in milliseconds
  25886. /** If you need to check double click without raising a single click at first click, enable this flag */
  25887. Scene.ExclusiveDoubleClickMode = false;
  25888. return Scene;
  25889. }());
  25890. BABYLON.Scene = Scene;
  25891. })(BABYLON || (BABYLON = {}));
  25892. //# sourceMappingURL=babylon.scene.js.map
  25893. "use strict";
  25894. var BABYLON;
  25895. (function (BABYLON) {
  25896. /**
  25897. * Set of assets to keep when moving a scene into an asset container.
  25898. */
  25899. var KeepAssets = /** @class */ (function () {
  25900. function KeepAssets() {
  25901. /**
  25902. * Cameras to keep.
  25903. */
  25904. this.cameras = new Array();
  25905. /**
  25906. * Lights to keep.
  25907. */
  25908. this.lights = new Array();
  25909. /**
  25910. * Meshes to keep.
  25911. */
  25912. this.meshes = new Array();
  25913. /**
  25914. * Skeletons to keep.
  25915. */
  25916. this.skeletons = new Array();
  25917. /**
  25918. * ParticleSystems to keep.
  25919. */
  25920. this.particleSystems = new Array();
  25921. /**
  25922. * Animations to keep.
  25923. */
  25924. this.animations = new Array();
  25925. /**
  25926. * MultiMaterials to keep.
  25927. */
  25928. this.multiMaterials = new Array();
  25929. /**
  25930. * Materials to keep.
  25931. */
  25932. this.materials = new Array();
  25933. /**
  25934. * MorphTargetManagers to keep.
  25935. */
  25936. this.morphTargetManagers = new Array();
  25937. /**
  25938. * Geometries to keep.
  25939. */
  25940. this.geometries = new Array();
  25941. /**
  25942. * TransformNodes to keep.
  25943. */
  25944. this.transformNodes = new Array();
  25945. /**
  25946. * LensFlareSystems to keep.
  25947. */
  25948. this.lensFlareSystems = new Array();
  25949. /**
  25950. * ShadowGenerators to keep.
  25951. */
  25952. this.shadowGenerators = new Array();
  25953. /**
  25954. * ActionManagers to keep.
  25955. */
  25956. this.actionManagers = new Array();
  25957. /**
  25958. * Sounds to keep.
  25959. */
  25960. this.sounds = new Array();
  25961. }
  25962. return KeepAssets;
  25963. }());
  25964. BABYLON.KeepAssets = KeepAssets;
  25965. /**
  25966. * Container with a set of assets that can be added or removed from a scene.
  25967. */
  25968. var AssetContainer = /** @class */ (function () {
  25969. /**
  25970. * Instantiates an AssetContainer.
  25971. * @param scene The scene the AssetContainer belongs to.
  25972. */
  25973. function AssetContainer(scene) {
  25974. // Objects
  25975. /**
  25976. * Cameras populated in the container.
  25977. */
  25978. this.cameras = new Array();
  25979. /**
  25980. * Lights populated in the container.
  25981. */
  25982. this.lights = new Array();
  25983. /**
  25984. * Meshes populated in the container.
  25985. */
  25986. this.meshes = new Array();
  25987. /**
  25988. * Skeletons populated in the container.
  25989. */
  25990. this.skeletons = new Array();
  25991. /**
  25992. * ParticleSystems populated in the container.
  25993. */
  25994. this.particleSystems = new Array();
  25995. /**
  25996. * Animations populated in the container.
  25997. */
  25998. this.animations = new Array();
  25999. /**
  26000. * MultiMaterials populated in the container.
  26001. */
  26002. this.multiMaterials = new Array();
  26003. /**
  26004. * Materials populated in the container.
  26005. */
  26006. this.materials = new Array();
  26007. /**
  26008. * MorphTargetManagers populated in the container.
  26009. */
  26010. this.morphTargetManagers = new Array();
  26011. /**
  26012. * Geometries populated in the container.
  26013. */
  26014. this.geometries = new Array();
  26015. /**
  26016. * TransformNodes populated in the container.
  26017. */
  26018. this.transformNodes = new Array();
  26019. /**
  26020. * LensFlareSystems populated in the container.
  26021. */
  26022. this.lensFlareSystems = new Array();
  26023. /**
  26024. * ShadowGenerators populated in the container.
  26025. */
  26026. this.shadowGenerators = new Array();
  26027. /**
  26028. * ActionManagers populated in the container.
  26029. */
  26030. this.actionManagers = new Array();
  26031. /**
  26032. * Sounds populated in the container.
  26033. */
  26034. this.sounds = new Array();
  26035. this.scene = scene;
  26036. }
  26037. /**
  26038. * Adds all the assets from the container to the scene.
  26039. */
  26040. AssetContainer.prototype.addAllToScene = function () {
  26041. var _this = this;
  26042. this.cameras.forEach(function (o) {
  26043. _this.scene.addCamera(o);
  26044. });
  26045. this.lights.forEach(function (o) {
  26046. _this.scene.addLight(o);
  26047. });
  26048. this.meshes.forEach(function (o) {
  26049. _this.scene.addMesh(o);
  26050. });
  26051. this.skeletons.forEach(function (o) {
  26052. _this.scene.addSkeleton(o);
  26053. });
  26054. this.particleSystems.forEach(function (o) {
  26055. _this.scene.addParticleSystem(o);
  26056. });
  26057. this.animations.forEach(function (o) {
  26058. _this.scene.addAnimation(o);
  26059. });
  26060. this.multiMaterials.forEach(function (o) {
  26061. _this.scene.addMultiMaterial(o);
  26062. });
  26063. this.materials.forEach(function (o) {
  26064. _this.scene.addMaterial(o);
  26065. });
  26066. this.morphTargetManagers.forEach(function (o) {
  26067. _this.scene.addMorphTargetManager(o);
  26068. });
  26069. this.geometries.forEach(function (o) {
  26070. _this.scene.addGeometry(o);
  26071. });
  26072. this.transformNodes.forEach(function (o) {
  26073. _this.scene.addTransformNode(o);
  26074. });
  26075. this.lensFlareSystems.forEach(function (o) {
  26076. _this.scene.addLensFlareSystem(o);
  26077. });
  26078. this.actionManagers.forEach(function (o) {
  26079. _this.scene.addActionManager(o);
  26080. });
  26081. this.sounds.forEach(function (o) {
  26082. o.play();
  26083. o.autoplay = true;
  26084. _this.scene.mainSoundTrack.AddSound(o);
  26085. });
  26086. };
  26087. /**
  26088. * Removes all the assets in the container from the scene
  26089. */
  26090. AssetContainer.prototype.removeAllFromScene = function () {
  26091. var _this = this;
  26092. this.cameras.forEach(function (o) {
  26093. _this.scene.removeCamera(o);
  26094. });
  26095. this.lights.forEach(function (o) {
  26096. _this.scene.removeLight(o);
  26097. });
  26098. this.meshes.forEach(function (o) {
  26099. _this.scene.removeMesh(o);
  26100. });
  26101. this.skeletons.forEach(function (o) {
  26102. _this.scene.removeSkeleton(o);
  26103. });
  26104. this.particleSystems.forEach(function (o) {
  26105. _this.scene.removeParticleSystem(o);
  26106. });
  26107. this.animations.forEach(function (o) {
  26108. _this.scene.removeAnimation(o);
  26109. });
  26110. this.multiMaterials.forEach(function (o) {
  26111. _this.scene.removeMultiMaterial(o);
  26112. });
  26113. this.materials.forEach(function (o) {
  26114. _this.scene.removeMaterial(o);
  26115. });
  26116. this.morphTargetManagers.forEach(function (o) {
  26117. _this.scene.removeMorphTargetManager(o);
  26118. });
  26119. this.geometries.forEach(function (o) {
  26120. _this.scene.removeGeometry(o);
  26121. });
  26122. this.transformNodes.forEach(function (o) {
  26123. _this.scene.removeTransformNode(o);
  26124. });
  26125. this.lensFlareSystems.forEach(function (o) {
  26126. _this.scene.removeLensFlareSystem(o);
  26127. });
  26128. this.actionManagers.forEach(function (o) {
  26129. _this.scene.removeActionManager(o);
  26130. });
  26131. this.sounds.forEach(function (o) {
  26132. o.stop();
  26133. o.autoplay = false;
  26134. _this.scene.mainSoundTrack.RemoveSound(o);
  26135. });
  26136. };
  26137. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26138. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26139. var asset = sourceAssets_1[_i];
  26140. var move = true;
  26141. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26142. var keepAsset = keepAssets_1[_a];
  26143. if (asset === keepAsset) {
  26144. move = false;
  26145. break;
  26146. }
  26147. }
  26148. if (move) {
  26149. targetAssets.push(asset);
  26150. }
  26151. }
  26152. };
  26153. /**
  26154. * Removes all the assets contained in the scene and adds them to the container.
  26155. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26156. */
  26157. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26158. if (keepAssets === undefined) {
  26159. keepAssets = new KeepAssets();
  26160. }
  26161. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26162. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26163. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26164. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26165. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26166. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26167. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26168. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26169. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26170. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26171. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26172. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26173. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26174. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26175. this.removeAllFromScene();
  26176. };
  26177. return AssetContainer;
  26178. }());
  26179. BABYLON.AssetContainer = AssetContainer;
  26180. })(BABYLON || (BABYLON = {}));
  26181. //# sourceMappingURL=babylon.assetContainer.js.map
  26182. "use strict";
  26183. var BABYLON;
  26184. (function (BABYLON) {
  26185. var Buffer = /** @class */ (function () {
  26186. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26187. if (instanced === void 0) { instanced = false; }
  26188. if (engine instanceof BABYLON.Mesh) {
  26189. this._engine = engine.getScene().getEngine();
  26190. }
  26191. else {
  26192. this._engine = engine;
  26193. }
  26194. this._updatable = updatable;
  26195. this._instanced = instanced;
  26196. this._data = data;
  26197. this._strideSize = stride;
  26198. if (!postponeInternalCreation) {
  26199. this.create();
  26200. }
  26201. }
  26202. /**
  26203. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26204. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26205. * @param offset defines offset in the buffer (0 by default)
  26206. * @param size defines the size in floats of attributes (position is 3 for instance)
  26207. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26208. * @param instanced defines if the vertex buffer contains indexed data
  26209. * @returns the new vertex buffer
  26210. */
  26211. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26212. // a lot of these parameters are ignored as they are overriden by the buffer
  26213. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26214. };
  26215. // Properties
  26216. Buffer.prototype.isUpdatable = function () {
  26217. return this._updatable;
  26218. };
  26219. Buffer.prototype.getData = function () {
  26220. return this._data;
  26221. };
  26222. Buffer.prototype.getBuffer = function () {
  26223. return this._buffer;
  26224. };
  26225. Buffer.prototype.getStrideSize = function () {
  26226. return this._strideSize;
  26227. };
  26228. // public getIsInstanced(): boolean {
  26229. // return this._instanced;
  26230. // }
  26231. // public get instanceDivisor(): number {
  26232. // return this._instanceDivisor;
  26233. // }
  26234. // public set instanceDivisor(value: number) {
  26235. // this._instanceDivisor = value;
  26236. // if (value == 0) {
  26237. // this._instanced = false;
  26238. // } else {
  26239. // this._instanced = true;
  26240. // }
  26241. // }
  26242. // Methods
  26243. Buffer.prototype.create = function (data) {
  26244. if (data === void 0) { data = null; }
  26245. if (!data && this._buffer) {
  26246. return; // nothing to do
  26247. }
  26248. data = data || this._data;
  26249. if (!data) {
  26250. return;
  26251. }
  26252. if (!this._buffer) {
  26253. if (this._updatable) {
  26254. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26255. this._data = data;
  26256. }
  26257. else {
  26258. this._buffer = this._engine.createVertexBuffer(data);
  26259. }
  26260. }
  26261. else if (this._updatable) {
  26262. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26263. this._data = data;
  26264. }
  26265. };
  26266. Buffer.prototype._rebuild = function () {
  26267. this._buffer = null;
  26268. this.create(this._data);
  26269. };
  26270. Buffer.prototype.update = function (data) {
  26271. this.create(data);
  26272. };
  26273. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26274. if (!this._buffer) {
  26275. return;
  26276. }
  26277. if (this._updatable) {
  26278. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26279. this._data = null;
  26280. }
  26281. };
  26282. Buffer.prototype.dispose = function () {
  26283. if (!this._buffer) {
  26284. return;
  26285. }
  26286. if (this._engine._releaseBuffer(this._buffer)) {
  26287. this._buffer = null;
  26288. }
  26289. };
  26290. return Buffer;
  26291. }());
  26292. BABYLON.Buffer = Buffer;
  26293. })(BABYLON || (BABYLON = {}));
  26294. //# sourceMappingURL=babylon.buffer.js.map
  26295. "use strict";
  26296. var BABYLON;
  26297. (function (BABYLON) {
  26298. var VertexBuffer = /** @class */ (function () {
  26299. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26300. if (data instanceof BABYLON.Buffer) {
  26301. if (!stride) {
  26302. stride = data.getStrideSize();
  26303. }
  26304. this._buffer = data;
  26305. this._ownsBuffer = false;
  26306. }
  26307. else {
  26308. if (!stride) {
  26309. stride = VertexBuffer.DeduceStride(kind);
  26310. }
  26311. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26312. this._ownsBuffer = true;
  26313. }
  26314. this._stride = stride;
  26315. this._instanced = instanced !== undefined ? instanced : false;
  26316. this._instanceDivisor = instanced ? 1 : 0;
  26317. this._offset = offset ? offset : 0;
  26318. this._size = size ? size : stride;
  26319. this._kind = kind;
  26320. }
  26321. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26322. /**
  26323. * Gets or sets the instance divisor when in instanced mode
  26324. */
  26325. get: function () {
  26326. return this._instanceDivisor;
  26327. },
  26328. set: function (value) {
  26329. this._instanceDivisor = value;
  26330. if (value == 0) {
  26331. this._instanced = false;
  26332. }
  26333. else {
  26334. this._instanced = true;
  26335. }
  26336. },
  26337. enumerable: true,
  26338. configurable: true
  26339. });
  26340. VertexBuffer.prototype._rebuild = function () {
  26341. if (!this._buffer) {
  26342. return;
  26343. }
  26344. this._buffer._rebuild();
  26345. };
  26346. /**
  26347. * Returns the kind of the VertexBuffer (string).
  26348. */
  26349. VertexBuffer.prototype.getKind = function () {
  26350. return this._kind;
  26351. };
  26352. // Properties
  26353. /**
  26354. * Boolean : is the VertexBuffer updatable ?
  26355. */
  26356. VertexBuffer.prototype.isUpdatable = function () {
  26357. return this._buffer.isUpdatable();
  26358. };
  26359. /**
  26360. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26361. */
  26362. VertexBuffer.prototype.getData = function () {
  26363. return this._buffer.getData();
  26364. };
  26365. /**
  26366. * Returns the WebGLBuffer associated to the VertexBuffer.
  26367. */
  26368. VertexBuffer.prototype.getBuffer = function () {
  26369. return this._buffer.getBuffer();
  26370. };
  26371. /**
  26372. * Returns the stride of the VertexBuffer (integer).
  26373. */
  26374. VertexBuffer.prototype.getStrideSize = function () {
  26375. return this._stride;
  26376. };
  26377. /**
  26378. * Returns the offset (integer).
  26379. */
  26380. VertexBuffer.prototype.getOffset = function () {
  26381. return this._offset;
  26382. };
  26383. /**
  26384. * Returns the VertexBuffer total size (integer).
  26385. */
  26386. VertexBuffer.prototype.getSize = function () {
  26387. return this._size;
  26388. };
  26389. /**
  26390. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26391. */
  26392. VertexBuffer.prototype.getIsInstanced = function () {
  26393. return this._instanced;
  26394. };
  26395. /**
  26396. * Returns the instancing divisor, zero for non-instanced (integer).
  26397. */
  26398. VertexBuffer.prototype.getInstanceDivisor = function () {
  26399. return this._instanceDivisor;
  26400. };
  26401. // Methods
  26402. /**
  26403. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26404. * Returns the created WebGLBuffer.
  26405. */
  26406. VertexBuffer.prototype.create = function (data) {
  26407. return this._buffer.create(data);
  26408. };
  26409. /**
  26410. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26411. * This function will create a new buffer if the current one is not updatable
  26412. * Returns the updated WebGLBuffer.
  26413. */
  26414. VertexBuffer.prototype.update = function (data) {
  26415. return this._buffer.update(data);
  26416. };
  26417. /**
  26418. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26419. * Returns the directly updated WebGLBuffer.
  26420. */
  26421. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26422. return this._buffer.updateDirectly(data, offset);
  26423. };
  26424. /**
  26425. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26426. */
  26427. VertexBuffer.prototype.dispose = function () {
  26428. if (this._ownsBuffer) {
  26429. this._buffer.dispose();
  26430. }
  26431. };
  26432. Object.defineProperty(VertexBuffer, "PositionKind", {
  26433. get: function () {
  26434. return VertexBuffer._PositionKind;
  26435. },
  26436. enumerable: true,
  26437. configurable: true
  26438. });
  26439. Object.defineProperty(VertexBuffer, "NormalKind", {
  26440. get: function () {
  26441. return VertexBuffer._NormalKind;
  26442. },
  26443. enumerable: true,
  26444. configurable: true
  26445. });
  26446. Object.defineProperty(VertexBuffer, "TangentKind", {
  26447. get: function () {
  26448. return VertexBuffer._TangentKind;
  26449. },
  26450. enumerable: true,
  26451. configurable: true
  26452. });
  26453. Object.defineProperty(VertexBuffer, "UVKind", {
  26454. get: function () {
  26455. return VertexBuffer._UVKind;
  26456. },
  26457. enumerable: true,
  26458. configurable: true
  26459. });
  26460. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26461. get: function () {
  26462. return VertexBuffer._UV2Kind;
  26463. },
  26464. enumerable: true,
  26465. configurable: true
  26466. });
  26467. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26468. get: function () {
  26469. return VertexBuffer._UV3Kind;
  26470. },
  26471. enumerable: true,
  26472. configurable: true
  26473. });
  26474. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26475. get: function () {
  26476. return VertexBuffer._UV4Kind;
  26477. },
  26478. enumerable: true,
  26479. configurable: true
  26480. });
  26481. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26482. get: function () {
  26483. return VertexBuffer._UV5Kind;
  26484. },
  26485. enumerable: true,
  26486. configurable: true
  26487. });
  26488. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26489. get: function () {
  26490. return VertexBuffer._UV6Kind;
  26491. },
  26492. enumerable: true,
  26493. configurable: true
  26494. });
  26495. Object.defineProperty(VertexBuffer, "ColorKind", {
  26496. get: function () {
  26497. return VertexBuffer._ColorKind;
  26498. },
  26499. enumerable: true,
  26500. configurable: true
  26501. });
  26502. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26503. get: function () {
  26504. return VertexBuffer._MatricesIndicesKind;
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26510. get: function () {
  26511. return VertexBuffer._MatricesWeightsKind;
  26512. },
  26513. enumerable: true,
  26514. configurable: true
  26515. });
  26516. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26517. get: function () {
  26518. return VertexBuffer._MatricesIndicesExtraKind;
  26519. },
  26520. enumerable: true,
  26521. configurable: true
  26522. });
  26523. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26524. get: function () {
  26525. return VertexBuffer._MatricesWeightsExtraKind;
  26526. },
  26527. enumerable: true,
  26528. configurable: true
  26529. });
  26530. /**
  26531. * Deduces the stride given a kind.
  26532. * @param kind The kind string to deduce
  26533. * @returns The deduced stride
  26534. */
  26535. VertexBuffer.DeduceStride = function (kind) {
  26536. switch (kind) {
  26537. case VertexBuffer.UVKind:
  26538. case VertexBuffer.UV2Kind:
  26539. case VertexBuffer.UV3Kind:
  26540. case VertexBuffer.UV4Kind:
  26541. case VertexBuffer.UV5Kind:
  26542. case VertexBuffer.UV6Kind:
  26543. return 2;
  26544. case VertexBuffer.NormalKind:
  26545. case VertexBuffer.PositionKind:
  26546. return 3;
  26547. case VertexBuffer.ColorKind:
  26548. case VertexBuffer.MatricesIndicesKind:
  26549. case VertexBuffer.MatricesIndicesExtraKind:
  26550. case VertexBuffer.MatricesWeightsKind:
  26551. case VertexBuffer.MatricesWeightsExtraKind:
  26552. case VertexBuffer.TangentKind:
  26553. return 4;
  26554. default:
  26555. throw new Error("Invalid kind '" + kind + "'");
  26556. }
  26557. };
  26558. // Enums
  26559. VertexBuffer._PositionKind = "position";
  26560. VertexBuffer._NormalKind = "normal";
  26561. VertexBuffer._TangentKind = "tangent";
  26562. VertexBuffer._UVKind = "uv";
  26563. VertexBuffer._UV2Kind = "uv2";
  26564. VertexBuffer._UV3Kind = "uv3";
  26565. VertexBuffer._UV4Kind = "uv4";
  26566. VertexBuffer._UV5Kind = "uv5";
  26567. VertexBuffer._UV6Kind = "uv6";
  26568. VertexBuffer._ColorKind = "color";
  26569. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26570. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26571. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26572. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26573. return VertexBuffer;
  26574. }());
  26575. BABYLON.VertexBuffer = VertexBuffer;
  26576. })(BABYLON || (BABYLON = {}));
  26577. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26578. "use strict";
  26579. var BABYLON;
  26580. (function (BABYLON) {
  26581. /**
  26582. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26583. */
  26584. var DummyInternalTextureTracker = /** @class */ (function () {
  26585. function DummyInternalTextureTracker() {
  26586. /**
  26587. * Gets or set the previous tracker in the list
  26588. */
  26589. this.previous = null;
  26590. /**
  26591. * Gets or set the next tracker in the list
  26592. */
  26593. this.next = null;
  26594. }
  26595. return DummyInternalTextureTracker;
  26596. }());
  26597. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26598. })(BABYLON || (BABYLON = {}));
  26599. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26600. "use strict";
  26601. var BABYLON;
  26602. (function (BABYLON) {
  26603. /**
  26604. * Class used to store data associated with WebGL texture data for the engine
  26605. * This class should not be used directly
  26606. */
  26607. var InternalTexture = /** @class */ (function () {
  26608. /**
  26609. * Creates a new InternalTexture
  26610. * @param engine defines the engine to use
  26611. * @param dataSource defines the type of data that will be used
  26612. */
  26613. function InternalTexture(engine, dataSource) {
  26614. /**
  26615. * Observable called when the texture is loaded
  26616. */
  26617. this.onLoadedObservable = new BABYLON.Observable();
  26618. /**
  26619. * Gets or set the previous tracker in the list
  26620. */
  26621. this.previous = null;
  26622. /**
  26623. * Gets or set the next tracker in the list
  26624. */
  26625. this.next = null;
  26626. // Private
  26627. /** @ignore */
  26628. this._initialSlot = -1;
  26629. /** @ignore */
  26630. this._designatedSlot = -1;
  26631. /** @ignore */
  26632. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26633. /** @ignore */
  26634. this._comparisonFunction = 0;
  26635. /** @ignore */
  26636. this._references = 1;
  26637. this._engine = engine;
  26638. this._dataSource = dataSource;
  26639. this._webGLTexture = engine._createTexture();
  26640. }
  26641. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26642. /**
  26643. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26644. */
  26645. get: function () {
  26646. return this._dataSource;
  26647. },
  26648. enumerable: true,
  26649. configurable: true
  26650. });
  26651. /**
  26652. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26653. */
  26654. InternalTexture.prototype.incrementReferences = function () {
  26655. this._references++;
  26656. };
  26657. /**
  26658. * Change the size of the texture (not the size of the content)
  26659. * @param width defines the new width
  26660. * @param height defines the new height
  26661. * @param depth defines the new depth (1 by default)
  26662. */
  26663. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26664. if (depth === void 0) { depth = 1; }
  26665. this.width = width;
  26666. this.height = height;
  26667. this.depth = depth;
  26668. this.baseWidth = width;
  26669. this.baseHeight = height;
  26670. this.baseDepth = depth;
  26671. this._size = width * height * depth;
  26672. };
  26673. /** @ignore */
  26674. InternalTexture.prototype._rebuild = function () {
  26675. var _this = this;
  26676. var proxy;
  26677. this.isReady = false;
  26678. this._cachedCoordinatesMode = null;
  26679. this._cachedWrapU = null;
  26680. this._cachedWrapV = null;
  26681. this._cachedAnisotropicFilteringLevel = null;
  26682. switch (this._dataSource) {
  26683. case InternalTexture.DATASOURCE_TEMP:
  26684. return;
  26685. case InternalTexture.DATASOURCE_URL:
  26686. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26687. _this.isReady = true;
  26688. }, null, this._buffer, undefined, this.format);
  26689. proxy._swapAndDie(this);
  26690. return;
  26691. case InternalTexture.DATASOURCE_RAW:
  26692. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26693. proxy._swapAndDie(this);
  26694. this.isReady = true;
  26695. return;
  26696. case InternalTexture.DATASOURCE_RAW3D:
  26697. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26698. proxy._swapAndDie(this);
  26699. this.isReady = true;
  26700. return;
  26701. case InternalTexture.DATASOURCE_DYNAMIC:
  26702. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26703. proxy._swapAndDie(this);
  26704. // The engine will make sure to update content so no need to flag it as isReady = true
  26705. return;
  26706. case InternalTexture.DATASOURCE_RENDERTARGET:
  26707. var options = new BABYLON.RenderTargetCreationOptions();
  26708. options.generateDepthBuffer = this._generateDepthBuffer;
  26709. options.generateMipMaps = this.generateMipMaps;
  26710. options.generateStencilBuffer = this._generateStencilBuffer;
  26711. options.samplingMode = this.samplingMode;
  26712. options.type = this.type;
  26713. if (this.isCube) {
  26714. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26715. }
  26716. else {
  26717. var size = {
  26718. width: this.width,
  26719. height: this.height
  26720. };
  26721. proxy = this._engine.createRenderTargetTexture(size, options);
  26722. }
  26723. proxy._swapAndDie(this);
  26724. this.isReady = true;
  26725. return;
  26726. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26727. var depthTextureOptions = {
  26728. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26729. comparisonFunction: this._comparisonFunction,
  26730. generateStencil: this._generateStencilBuffer,
  26731. isCube: this.isCube
  26732. };
  26733. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26734. proxy._swapAndDie(this);
  26735. this.isReady = true;
  26736. return;
  26737. case InternalTexture.DATASOURCE_CUBE:
  26738. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26739. _this.isReady = true;
  26740. }, null, this.format, this._extension);
  26741. proxy._swapAndDie(this);
  26742. return;
  26743. case InternalTexture.DATASOURCE_CUBERAW:
  26744. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26745. proxy._swapAndDie(this);
  26746. this.isReady = true;
  26747. return;
  26748. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26749. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26750. if (proxy) {
  26751. proxy._swapAndDie(_this);
  26752. }
  26753. _this.isReady = true;
  26754. }, null, this.format, this._extension);
  26755. return;
  26756. }
  26757. };
  26758. InternalTexture.prototype._swapAndDie = function (target) {
  26759. target._webGLTexture = this._webGLTexture;
  26760. if (this._framebuffer) {
  26761. target._framebuffer = this._framebuffer;
  26762. }
  26763. if (this._depthStencilBuffer) {
  26764. target._depthStencilBuffer = this._depthStencilBuffer;
  26765. }
  26766. if (this._lodTextureHigh) {
  26767. if (target._lodTextureHigh) {
  26768. target._lodTextureHigh.dispose();
  26769. }
  26770. target._lodTextureHigh = this._lodTextureHigh;
  26771. }
  26772. if (this._lodTextureMid) {
  26773. if (target._lodTextureMid) {
  26774. target._lodTextureMid.dispose();
  26775. }
  26776. target._lodTextureMid = this._lodTextureMid;
  26777. }
  26778. if (this._lodTextureLow) {
  26779. if (target._lodTextureLow) {
  26780. target._lodTextureLow.dispose();
  26781. }
  26782. target._lodTextureLow = this._lodTextureLow;
  26783. }
  26784. var cache = this._engine.getLoadedTexturesCache();
  26785. var index = cache.indexOf(this);
  26786. if (index !== -1) {
  26787. cache.splice(index, 1);
  26788. }
  26789. };
  26790. /**
  26791. * Dispose the current allocated resources
  26792. */
  26793. InternalTexture.prototype.dispose = function () {
  26794. if (!this._webGLTexture) {
  26795. return;
  26796. }
  26797. this._references--;
  26798. if (this._references === 0) {
  26799. this._engine._releaseTexture(this);
  26800. this._webGLTexture = null;
  26801. this.previous = null;
  26802. this.next = null;
  26803. }
  26804. };
  26805. /**
  26806. * The source of the texture data is unknown
  26807. */
  26808. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26809. /**
  26810. * Texture data comes from an URL
  26811. */
  26812. InternalTexture.DATASOURCE_URL = 1;
  26813. /**
  26814. * Texture data is only used for temporary storage
  26815. */
  26816. InternalTexture.DATASOURCE_TEMP = 2;
  26817. /**
  26818. * Texture data comes from raw data (ArrayBuffer)
  26819. */
  26820. InternalTexture.DATASOURCE_RAW = 3;
  26821. /**
  26822. * Texture content is dynamic (video or dynamic texture)
  26823. */
  26824. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26825. /**
  26826. * Texture content is generated by rendering to it
  26827. */
  26828. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26829. /**
  26830. * Texture content is part of a multi render target process
  26831. */
  26832. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26833. /**
  26834. * Texture data comes from a cube data file
  26835. */
  26836. InternalTexture.DATASOURCE_CUBE = 7;
  26837. /**
  26838. * Texture data comes from a raw cube data
  26839. */
  26840. InternalTexture.DATASOURCE_CUBERAW = 8;
  26841. /**
  26842. * Texture data come from a prefiltered cube data file
  26843. */
  26844. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26845. /**
  26846. * Texture content is raw 3D data
  26847. */
  26848. InternalTexture.DATASOURCE_RAW3D = 10;
  26849. /**
  26850. * Texture content is a depth texture
  26851. */
  26852. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26853. return InternalTexture;
  26854. }());
  26855. BABYLON.InternalTexture = InternalTexture;
  26856. })(BABYLON || (BABYLON = {}));
  26857. //# sourceMappingURL=babylon.internalTexture.js.map
  26858. "use strict";
  26859. var BABYLON;
  26860. (function (BABYLON) {
  26861. var BaseTexture = /** @class */ (function () {
  26862. function BaseTexture(scene) {
  26863. this._hasAlpha = false;
  26864. this.getAlphaFromRGB = false;
  26865. this.level = 1;
  26866. this.coordinatesIndex = 0;
  26867. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26868. /**
  26869. * | Value | Type | Description |
  26870. * | ----- | ------------------ | ----------- |
  26871. * | 0 | CLAMP_ADDRESSMODE | |
  26872. * | 1 | WRAP_ADDRESSMODE | |
  26873. * | 2 | MIRROR_ADDRESSMODE | |
  26874. */
  26875. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26876. /**
  26877. * | Value | Type | Description |
  26878. * | ----- | ------------------ | ----------- |
  26879. * | 0 | CLAMP_ADDRESSMODE | |
  26880. * | 1 | WRAP_ADDRESSMODE | |
  26881. * | 2 | MIRROR_ADDRESSMODE | |
  26882. */
  26883. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26884. /**
  26885. * | Value | Type | Description |
  26886. * | ----- | ------------------ | ----------- |
  26887. * | 0 | CLAMP_ADDRESSMODE | |
  26888. * | 1 | WRAP_ADDRESSMODE | |
  26889. * | 2 | MIRROR_ADDRESSMODE | |
  26890. */
  26891. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26892. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26893. this.isCube = false;
  26894. this.is3D = false;
  26895. this.gammaSpace = true;
  26896. this.invertZ = false;
  26897. this.lodLevelInAlpha = false;
  26898. this.lodGenerationOffset = 0.0;
  26899. this.lodGenerationScale = 0.8;
  26900. this.isRenderTarget = false;
  26901. this.animations = new Array();
  26902. /**
  26903. * An event triggered when the texture is disposed.
  26904. * @type {BABYLON.Observable}
  26905. */
  26906. this.onDisposeObservable = new BABYLON.Observable();
  26907. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26908. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26909. if (this._scene) {
  26910. this._scene.textures.push(this);
  26911. }
  26912. this._uid = null;
  26913. }
  26914. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26915. get: function () {
  26916. return this._hasAlpha;
  26917. },
  26918. set: function (value) {
  26919. if (this._hasAlpha === value) {
  26920. return;
  26921. }
  26922. this._hasAlpha = value;
  26923. if (this._scene) {
  26924. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26925. }
  26926. },
  26927. enumerable: true,
  26928. configurable: true
  26929. });
  26930. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26931. get: function () {
  26932. return this._coordinatesMode;
  26933. },
  26934. /**
  26935. * How a texture is mapped.
  26936. *
  26937. * | Value | Type | Description |
  26938. * | ----- | ----------------------------------- | ----------- |
  26939. * | 0 | EXPLICIT_MODE | |
  26940. * | 1 | SPHERICAL_MODE | |
  26941. * | 2 | PLANAR_MODE | |
  26942. * | 3 | CUBIC_MODE | |
  26943. * | 4 | PROJECTION_MODE | |
  26944. * | 5 | SKYBOX_MODE | |
  26945. * | 6 | INVCUBIC_MODE | |
  26946. * | 7 | EQUIRECTANGULAR_MODE | |
  26947. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26948. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26949. */
  26950. set: function (value) {
  26951. if (this._coordinatesMode === value) {
  26952. return;
  26953. }
  26954. this._coordinatesMode = value;
  26955. if (this._scene) {
  26956. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26957. }
  26958. },
  26959. enumerable: true,
  26960. configurable: true
  26961. });
  26962. Object.defineProperty(BaseTexture.prototype, "uid", {
  26963. get: function () {
  26964. if (!this._uid) {
  26965. this._uid = BABYLON.Tools.RandomId();
  26966. }
  26967. return this._uid;
  26968. },
  26969. enumerable: true,
  26970. configurable: true
  26971. });
  26972. BaseTexture.prototype.toString = function () {
  26973. return this.name;
  26974. };
  26975. BaseTexture.prototype.getClassName = function () {
  26976. return "BaseTexture";
  26977. };
  26978. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26979. set: function (callback) {
  26980. if (this._onDisposeObserver) {
  26981. this.onDisposeObservable.remove(this._onDisposeObserver);
  26982. }
  26983. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26984. },
  26985. enumerable: true,
  26986. configurable: true
  26987. });
  26988. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26989. get: function () {
  26990. return true;
  26991. },
  26992. enumerable: true,
  26993. configurable: true
  26994. });
  26995. BaseTexture.prototype.getScene = function () {
  26996. return this._scene;
  26997. };
  26998. BaseTexture.prototype.getTextureMatrix = function () {
  26999. return BABYLON.Matrix.IdentityReadOnly;
  27000. };
  27001. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  27002. return BABYLON.Matrix.IdentityReadOnly;
  27003. };
  27004. BaseTexture.prototype.getInternalTexture = function () {
  27005. return this._texture;
  27006. };
  27007. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  27008. return !this.isBlocking || this.isReady();
  27009. };
  27010. BaseTexture.prototype.isReady = function () {
  27011. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27012. this.delayLoad();
  27013. return false;
  27014. }
  27015. if (this._texture) {
  27016. return this._texture.isReady;
  27017. }
  27018. return false;
  27019. };
  27020. BaseTexture.prototype.getSize = function () {
  27021. if (this._texture && this._texture.width) {
  27022. return new BABYLON.Size(this._texture.width, this._texture.height);
  27023. }
  27024. if (this._texture && this._texture._size) {
  27025. return new BABYLON.Size(this._texture._size, this._texture._size);
  27026. }
  27027. return BABYLON.Size.Zero();
  27028. };
  27029. BaseTexture.prototype.getBaseSize = function () {
  27030. if (!this.isReady() || !this._texture)
  27031. return BABYLON.Size.Zero();
  27032. if (this._texture._size) {
  27033. return new BABYLON.Size(this._texture._size, this._texture._size);
  27034. }
  27035. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27036. };
  27037. BaseTexture.prototype.scale = function (ratio) {
  27038. };
  27039. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27040. get: function () {
  27041. return false;
  27042. },
  27043. enumerable: true,
  27044. configurable: true
  27045. });
  27046. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27047. if (!this._scene) {
  27048. return null;
  27049. }
  27050. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27051. for (var index = 0; index < texturesCache.length; index++) {
  27052. var texturesCacheEntry = texturesCache[index];
  27053. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27054. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27055. texturesCacheEntry.incrementReferences();
  27056. return texturesCacheEntry;
  27057. }
  27058. }
  27059. }
  27060. return null;
  27061. };
  27062. BaseTexture.prototype._rebuild = function () {
  27063. };
  27064. BaseTexture.prototype.delayLoad = function () {
  27065. };
  27066. BaseTexture.prototype.clone = function () {
  27067. return null;
  27068. };
  27069. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27070. get: function () {
  27071. if (!this._texture) {
  27072. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27073. }
  27074. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27075. },
  27076. enumerable: true,
  27077. configurable: true
  27078. });
  27079. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27080. get: function () {
  27081. if (!this._texture) {
  27082. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27083. }
  27084. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27085. },
  27086. enumerable: true,
  27087. configurable: true
  27088. });
  27089. BaseTexture.prototype.readPixels = function (faceIndex) {
  27090. if (faceIndex === void 0) { faceIndex = 0; }
  27091. if (!this._texture) {
  27092. return null;
  27093. }
  27094. var size = this.getSize();
  27095. var scene = this.getScene();
  27096. if (!scene) {
  27097. return null;
  27098. }
  27099. var engine = scene.getEngine();
  27100. if (this._texture.isCube) {
  27101. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27102. }
  27103. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27104. };
  27105. BaseTexture.prototype.releaseInternalTexture = function () {
  27106. if (this._texture) {
  27107. this._texture.dispose();
  27108. this._texture = null;
  27109. }
  27110. };
  27111. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27112. get: function () {
  27113. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27114. return null;
  27115. }
  27116. if (!this._texture._sphericalPolynomial) {
  27117. this._texture._sphericalPolynomial =
  27118. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27119. }
  27120. return this._texture._sphericalPolynomial;
  27121. },
  27122. set: function (value) {
  27123. if (this._texture) {
  27124. this._texture._sphericalPolynomial = value;
  27125. }
  27126. },
  27127. enumerable: true,
  27128. configurable: true
  27129. });
  27130. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27131. get: function () {
  27132. if (this._texture) {
  27133. return this._texture._lodTextureHigh;
  27134. }
  27135. return null;
  27136. },
  27137. enumerable: true,
  27138. configurable: true
  27139. });
  27140. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27141. get: function () {
  27142. if (this._texture) {
  27143. return this._texture._lodTextureMid;
  27144. }
  27145. return null;
  27146. },
  27147. enumerable: true,
  27148. configurable: true
  27149. });
  27150. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27151. get: function () {
  27152. if (this._texture) {
  27153. return this._texture._lodTextureLow;
  27154. }
  27155. return null;
  27156. },
  27157. enumerable: true,
  27158. configurable: true
  27159. });
  27160. BaseTexture.prototype.dispose = function () {
  27161. if (!this._scene) {
  27162. return;
  27163. }
  27164. // Animations
  27165. this._scene.stopAnimation(this);
  27166. // Remove from scene
  27167. this._scene._removePendingData(this);
  27168. var index = this._scene.textures.indexOf(this);
  27169. if (index >= 0) {
  27170. this._scene.textures.splice(index, 1);
  27171. }
  27172. if (this._texture === undefined) {
  27173. return;
  27174. }
  27175. // Release
  27176. this.releaseInternalTexture();
  27177. // Callback
  27178. this.onDisposeObservable.notifyObservers(this);
  27179. this.onDisposeObservable.clear();
  27180. };
  27181. BaseTexture.prototype.serialize = function () {
  27182. if (!this.name) {
  27183. return null;
  27184. }
  27185. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27186. // Animations
  27187. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27188. return serializationObject;
  27189. };
  27190. BaseTexture.WhenAllReady = function (textures, callback) {
  27191. var numRemaining = textures.length;
  27192. if (numRemaining === 0) {
  27193. callback();
  27194. return;
  27195. }
  27196. var _loop_1 = function () {
  27197. texture = textures[i];
  27198. if (texture.isReady()) {
  27199. if (--numRemaining === 0) {
  27200. callback();
  27201. }
  27202. }
  27203. else {
  27204. onLoadObservable = texture.onLoadObservable;
  27205. var onLoadCallback_1 = function () {
  27206. onLoadObservable.removeCallback(onLoadCallback_1);
  27207. if (--numRemaining === 0) {
  27208. callback();
  27209. }
  27210. };
  27211. onLoadObservable.add(onLoadCallback_1);
  27212. }
  27213. };
  27214. var texture, onLoadObservable;
  27215. for (var i = 0; i < textures.length; i++) {
  27216. _loop_1();
  27217. }
  27218. };
  27219. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27220. __decorate([
  27221. BABYLON.serialize()
  27222. ], BaseTexture.prototype, "name", void 0);
  27223. __decorate([
  27224. BABYLON.serialize("hasAlpha")
  27225. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27229. __decorate([
  27230. BABYLON.serialize()
  27231. ], BaseTexture.prototype, "level", void 0);
  27232. __decorate([
  27233. BABYLON.serialize()
  27234. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27235. __decorate([
  27236. BABYLON.serialize("coordinatesMode")
  27237. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27238. __decorate([
  27239. BABYLON.serialize()
  27240. ], BaseTexture.prototype, "wrapU", void 0);
  27241. __decorate([
  27242. BABYLON.serialize()
  27243. ], BaseTexture.prototype, "wrapV", void 0);
  27244. __decorate([
  27245. BABYLON.serialize()
  27246. ], BaseTexture.prototype, "wrapR", void 0);
  27247. __decorate([
  27248. BABYLON.serialize()
  27249. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27250. __decorate([
  27251. BABYLON.serialize()
  27252. ], BaseTexture.prototype, "isCube", void 0);
  27253. __decorate([
  27254. BABYLON.serialize()
  27255. ], BaseTexture.prototype, "is3D", void 0);
  27256. __decorate([
  27257. BABYLON.serialize()
  27258. ], BaseTexture.prototype, "gammaSpace", void 0);
  27259. __decorate([
  27260. BABYLON.serialize()
  27261. ], BaseTexture.prototype, "invertZ", void 0);
  27262. __decorate([
  27263. BABYLON.serialize()
  27264. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27265. __decorate([
  27266. BABYLON.serialize()
  27267. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27268. __decorate([
  27269. BABYLON.serialize()
  27270. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27271. __decorate([
  27272. BABYLON.serialize()
  27273. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27274. return BaseTexture;
  27275. }());
  27276. BABYLON.BaseTexture = BaseTexture;
  27277. })(BABYLON || (BABYLON = {}));
  27278. //# sourceMappingURL=babylon.baseTexture.js.map
  27279. "use strict";
  27280. var BABYLON;
  27281. (function (BABYLON) {
  27282. var Texture = /** @class */ (function (_super) {
  27283. __extends(Texture, _super);
  27284. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27285. if (noMipmap === void 0) { noMipmap = false; }
  27286. if (invertY === void 0) { invertY = true; }
  27287. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27288. if (onLoad === void 0) { onLoad = null; }
  27289. if (onError === void 0) { onError = null; }
  27290. if (buffer === void 0) { buffer = null; }
  27291. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27292. var _this = _super.call(this, scene) || this;
  27293. _this.uOffset = 0;
  27294. _this.vOffset = 0;
  27295. _this.uScale = 1.0;
  27296. _this.vScale = 1.0;
  27297. _this.uAng = 0;
  27298. _this.vAng = 0;
  27299. _this.wAng = 0;
  27300. _this._isBlocking = true;
  27301. _this.name = url || "";
  27302. _this.url = url;
  27303. _this._noMipmap = noMipmap;
  27304. _this._invertY = invertY;
  27305. _this._samplingMode = samplingMode;
  27306. _this._buffer = buffer;
  27307. _this._deleteBuffer = deleteBuffer;
  27308. if (format) {
  27309. _this._format = format;
  27310. }
  27311. scene = _this.getScene();
  27312. if (!scene) {
  27313. return _this;
  27314. }
  27315. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27316. var load = function () {
  27317. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27318. _this.onLoadObservable.notifyObservers(_this);
  27319. }
  27320. if (onLoad) {
  27321. onLoad();
  27322. }
  27323. if (!_this.isBlocking && scene) {
  27324. scene.resetCachedMaterial();
  27325. }
  27326. };
  27327. if (!_this.url) {
  27328. _this._delayedOnLoad = load;
  27329. _this._delayedOnError = onError;
  27330. return _this;
  27331. }
  27332. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27333. if (!_this._texture) {
  27334. if (!scene.useDelayedTextureLoading) {
  27335. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27336. if (deleteBuffer) {
  27337. delete _this._buffer;
  27338. }
  27339. }
  27340. else {
  27341. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27342. _this._delayedOnLoad = load;
  27343. _this._delayedOnError = onError;
  27344. }
  27345. }
  27346. else {
  27347. if (_this._texture.isReady) {
  27348. BABYLON.Tools.SetImmediate(function () { return load(); });
  27349. }
  27350. else {
  27351. _this._texture.onLoadedObservable.add(load);
  27352. }
  27353. }
  27354. return _this;
  27355. }
  27356. Object.defineProperty(Texture.prototype, "noMipmap", {
  27357. get: function () {
  27358. return this._noMipmap;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. Object.defineProperty(Texture.prototype, "isBlocking", {
  27364. get: function () {
  27365. return this._isBlocking;
  27366. },
  27367. set: function (value) {
  27368. this._isBlocking = value;
  27369. },
  27370. enumerable: true,
  27371. configurable: true
  27372. });
  27373. Object.defineProperty(Texture.prototype, "samplingMode", {
  27374. get: function () {
  27375. return this._samplingMode;
  27376. },
  27377. enumerable: true,
  27378. configurable: true
  27379. });
  27380. Texture.prototype.updateURL = function (url) {
  27381. this.url = url;
  27382. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27383. this.delayLoad();
  27384. };
  27385. Texture.prototype.delayLoad = function () {
  27386. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27387. return;
  27388. }
  27389. var scene = this.getScene();
  27390. if (!scene) {
  27391. return;
  27392. }
  27393. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27394. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27395. if (!this._texture) {
  27396. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27397. if (this._deleteBuffer) {
  27398. delete this._buffer;
  27399. }
  27400. }
  27401. else {
  27402. if (this._delayedOnLoad) {
  27403. if (this._texture.isReady) {
  27404. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27405. }
  27406. else {
  27407. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27408. }
  27409. }
  27410. }
  27411. this._delayedOnLoad = null;
  27412. this._delayedOnError = null;
  27413. };
  27414. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27415. if (!this._texture) {
  27416. return;
  27417. }
  27418. var scene = this.getScene();
  27419. if (!scene) {
  27420. return;
  27421. }
  27422. this._samplingMode = samplingMode;
  27423. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27424. };
  27425. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27426. x *= this.uScale;
  27427. y *= this.vScale;
  27428. x -= 0.5 * this.uScale;
  27429. y -= 0.5 * this.vScale;
  27430. z -= 0.5;
  27431. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27432. t.x += 0.5 * this.uScale + this.uOffset;
  27433. t.y += 0.5 * this.vScale + this.vOffset;
  27434. t.z += 0.5;
  27435. };
  27436. Texture.prototype.getTextureMatrix = function () {
  27437. var _this = this;
  27438. if (this.uOffset === this._cachedUOffset &&
  27439. this.vOffset === this._cachedVOffset &&
  27440. this.uScale === this._cachedUScale &&
  27441. this.vScale === this._cachedVScale &&
  27442. this.uAng === this._cachedUAng &&
  27443. this.vAng === this._cachedVAng &&
  27444. this.wAng === this._cachedWAng) {
  27445. return this._cachedTextureMatrix;
  27446. }
  27447. this._cachedUOffset = this.uOffset;
  27448. this._cachedVOffset = this.vOffset;
  27449. this._cachedUScale = this.uScale;
  27450. this._cachedVScale = this.vScale;
  27451. this._cachedUAng = this.uAng;
  27452. this._cachedVAng = this.vAng;
  27453. this._cachedWAng = this.wAng;
  27454. if (!this._cachedTextureMatrix) {
  27455. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27456. this._rowGenerationMatrix = new BABYLON.Matrix();
  27457. this._t0 = BABYLON.Vector3.Zero();
  27458. this._t1 = BABYLON.Vector3.Zero();
  27459. this._t2 = BABYLON.Vector3.Zero();
  27460. }
  27461. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27462. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27463. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27464. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27465. this._t1.subtractInPlace(this._t0);
  27466. this._t2.subtractInPlace(this._t0);
  27467. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27468. this._cachedTextureMatrix.m[0] = this._t1.x;
  27469. this._cachedTextureMatrix.m[1] = this._t1.y;
  27470. this._cachedTextureMatrix.m[2] = this._t1.z;
  27471. this._cachedTextureMatrix.m[4] = this._t2.x;
  27472. this._cachedTextureMatrix.m[5] = this._t2.y;
  27473. this._cachedTextureMatrix.m[6] = this._t2.z;
  27474. this._cachedTextureMatrix.m[8] = this._t0.x;
  27475. this._cachedTextureMatrix.m[9] = this._t0.y;
  27476. this._cachedTextureMatrix.m[10] = this._t0.z;
  27477. var scene = this.getScene();
  27478. if (!scene) {
  27479. return this._cachedTextureMatrix;
  27480. }
  27481. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27482. return mat.hasTexture(_this);
  27483. });
  27484. return this._cachedTextureMatrix;
  27485. };
  27486. Texture.prototype.getReflectionTextureMatrix = function () {
  27487. var _this = this;
  27488. var scene = this.getScene();
  27489. if (!scene) {
  27490. return this._cachedTextureMatrix;
  27491. }
  27492. if (this.uOffset === this._cachedUOffset &&
  27493. this.vOffset === this._cachedVOffset &&
  27494. this.uScale === this._cachedUScale &&
  27495. this.vScale === this._cachedVScale &&
  27496. this.coordinatesMode === this._cachedCoordinatesMode) {
  27497. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27498. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27499. return this._cachedTextureMatrix;
  27500. }
  27501. }
  27502. else {
  27503. return this._cachedTextureMatrix;
  27504. }
  27505. }
  27506. if (!this._cachedTextureMatrix) {
  27507. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27508. }
  27509. if (!this._projectionModeMatrix) {
  27510. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27511. }
  27512. this._cachedUOffset = this.uOffset;
  27513. this._cachedVOffset = this.vOffset;
  27514. this._cachedUScale = this.uScale;
  27515. this._cachedVScale = this.vScale;
  27516. this._cachedCoordinatesMode = this.coordinatesMode;
  27517. switch (this.coordinatesMode) {
  27518. case Texture.PLANAR_MODE:
  27519. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27520. this._cachedTextureMatrix[0] = this.uScale;
  27521. this._cachedTextureMatrix[5] = this.vScale;
  27522. this._cachedTextureMatrix[12] = this.uOffset;
  27523. this._cachedTextureMatrix[13] = this.vOffset;
  27524. break;
  27525. case Texture.PROJECTION_MODE:
  27526. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27527. this._projectionModeMatrix.m[0] = 0.5;
  27528. this._projectionModeMatrix.m[5] = -0.5;
  27529. this._projectionModeMatrix.m[10] = 0.0;
  27530. this._projectionModeMatrix.m[12] = 0.5;
  27531. this._projectionModeMatrix.m[13] = 0.5;
  27532. this._projectionModeMatrix.m[14] = 1.0;
  27533. this._projectionModeMatrix.m[15] = 1.0;
  27534. var projectionMatrix = scene.getProjectionMatrix();
  27535. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27536. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27537. break;
  27538. default:
  27539. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27540. break;
  27541. }
  27542. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27543. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27544. });
  27545. return this._cachedTextureMatrix;
  27546. };
  27547. Texture.prototype.clone = function () {
  27548. var _this = this;
  27549. return BABYLON.SerializationHelper.Clone(function () {
  27550. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27551. }, this);
  27552. };
  27553. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27554. get: function () {
  27555. if (!this._onLoadObservable) {
  27556. this._onLoadObservable = new BABYLON.Observable();
  27557. }
  27558. return this._onLoadObservable;
  27559. },
  27560. enumerable: true,
  27561. configurable: true
  27562. });
  27563. Texture.prototype.serialize = function () {
  27564. var serializationObject = _super.prototype.serialize.call(this);
  27565. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27566. serializationObject.base64String = this._buffer;
  27567. serializationObject.name = serializationObject.name.replace("data:", "");
  27568. }
  27569. return serializationObject;
  27570. };
  27571. Texture.prototype.getClassName = function () {
  27572. return "Texture";
  27573. };
  27574. Texture.prototype.dispose = function () {
  27575. _super.prototype.dispose.call(this);
  27576. if (this.onLoadObservable) {
  27577. this.onLoadObservable.clear();
  27578. this._onLoadObservable = null;
  27579. }
  27580. this._delayedOnLoad = null;
  27581. this._delayedOnError = null;
  27582. };
  27583. // Statics
  27584. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27585. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27586. if (onLoad === void 0) { onLoad = null; }
  27587. if (onError === void 0) { onError = null; }
  27588. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27589. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27590. };
  27591. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27592. if (parsedTexture.customType) {
  27593. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27594. // Update Sampling Mode
  27595. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27596. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27597. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27598. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27599. }
  27600. }
  27601. return parsedCustomTexture;
  27602. }
  27603. if (parsedTexture.isCube) {
  27604. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27605. }
  27606. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27607. return null;
  27608. }
  27609. var texture = BABYLON.SerializationHelper.Parse(function () {
  27610. var generateMipMaps = true;
  27611. if (parsedTexture.noMipmap) {
  27612. generateMipMaps = false;
  27613. }
  27614. if (parsedTexture.mirrorPlane) {
  27615. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27616. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27617. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27618. return mirrorTexture;
  27619. }
  27620. else if (parsedTexture.isRenderTarget) {
  27621. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27622. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27623. return renderTargetTexture;
  27624. }
  27625. else {
  27626. var texture;
  27627. if (parsedTexture.base64String) {
  27628. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27629. }
  27630. else {
  27631. var url = rootUrl + parsedTexture.name;
  27632. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27633. url = parsedTexture.url;
  27634. }
  27635. texture = new Texture(url, scene, !generateMipMaps);
  27636. }
  27637. return texture;
  27638. }
  27639. }, parsedTexture, scene);
  27640. // Update Sampling Mode
  27641. if (parsedTexture.samplingMode) {
  27642. var sampling = parsedTexture.samplingMode;
  27643. if (texture._samplingMode !== sampling) {
  27644. texture.updateSamplingMode(sampling);
  27645. }
  27646. }
  27647. // Animations
  27648. if (parsedTexture.animations) {
  27649. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27650. var parsedAnimation = parsedTexture.animations[animationIndex];
  27651. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27652. }
  27653. }
  27654. return texture;
  27655. };
  27656. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27657. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27658. if (noMipmap === void 0) { noMipmap = false; }
  27659. if (invertY === void 0) { invertY = true; }
  27660. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27661. if (onLoad === void 0) { onLoad = null; }
  27662. if (onError === void 0) { onError = null; }
  27663. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27664. if (name.substr(0, 5) !== "data:") {
  27665. name = "data:" + name;
  27666. }
  27667. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27668. };
  27669. // Constants
  27670. Texture.NEAREST_SAMPLINGMODE = 1;
  27671. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27672. Texture.BILINEAR_SAMPLINGMODE = 2;
  27673. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27674. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27675. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27676. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27677. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27678. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27679. Texture.NEAREST_LINEAR = 7;
  27680. Texture.NEAREST_NEAREST = 8;
  27681. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27682. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27683. Texture.LINEAR_LINEAR = 11;
  27684. Texture.LINEAR_NEAREST = 12;
  27685. Texture.EXPLICIT_MODE = 0;
  27686. Texture.SPHERICAL_MODE = 1;
  27687. Texture.PLANAR_MODE = 2;
  27688. Texture.CUBIC_MODE = 3;
  27689. Texture.PROJECTION_MODE = 4;
  27690. Texture.SKYBOX_MODE = 5;
  27691. Texture.INVCUBIC_MODE = 6;
  27692. Texture.EQUIRECTANGULAR_MODE = 7;
  27693. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27694. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27695. Texture.CLAMP_ADDRESSMODE = 0;
  27696. Texture.WRAP_ADDRESSMODE = 1;
  27697. Texture.MIRROR_ADDRESSMODE = 2;
  27698. /**
  27699. * 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
  27700. */
  27701. Texture.UseSerializedUrlIfAny = false;
  27702. __decorate([
  27703. BABYLON.serialize()
  27704. ], Texture.prototype, "url", void 0);
  27705. __decorate([
  27706. BABYLON.serialize()
  27707. ], Texture.prototype, "uOffset", void 0);
  27708. __decorate([
  27709. BABYLON.serialize()
  27710. ], Texture.prototype, "vOffset", void 0);
  27711. __decorate([
  27712. BABYLON.serialize()
  27713. ], Texture.prototype, "uScale", void 0);
  27714. __decorate([
  27715. BABYLON.serialize()
  27716. ], Texture.prototype, "vScale", void 0);
  27717. __decorate([
  27718. BABYLON.serialize()
  27719. ], Texture.prototype, "uAng", void 0);
  27720. __decorate([
  27721. BABYLON.serialize()
  27722. ], Texture.prototype, "vAng", void 0);
  27723. __decorate([
  27724. BABYLON.serialize()
  27725. ], Texture.prototype, "wAng", void 0);
  27726. __decorate([
  27727. BABYLON.serialize()
  27728. ], Texture.prototype, "isBlocking", null);
  27729. return Texture;
  27730. }(BABYLON.BaseTexture));
  27731. BABYLON.Texture = Texture;
  27732. })(BABYLON || (BABYLON = {}));
  27733. //# sourceMappingURL=babylon.texture.js.map
  27734. "use strict";
  27735. var BABYLON;
  27736. (function (BABYLON) {
  27737. var _InstancesBatch = /** @class */ (function () {
  27738. function _InstancesBatch() {
  27739. this.mustReturn = false;
  27740. this.visibleInstances = new Array();
  27741. this.renderSelf = new Array();
  27742. }
  27743. return _InstancesBatch;
  27744. }());
  27745. BABYLON._InstancesBatch = _InstancesBatch;
  27746. var Mesh = /** @class */ (function (_super) {
  27747. __extends(Mesh, _super);
  27748. /**
  27749. * @constructor
  27750. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27751. * @param {Scene} scene The scene to add this mesh to.
  27752. * @param {Node} parent The parent of this mesh, if it has one
  27753. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27754. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27755. * When false, achieved by calling a clone(), also passing False.
  27756. * This will make creation of children, recursive.
  27757. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27758. */
  27759. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27760. if (scene === void 0) { scene = null; }
  27761. if (parent === void 0) { parent = null; }
  27762. if (source === void 0) { source = null; }
  27763. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27764. var _this = _super.call(this, name, scene) || this;
  27765. // Events
  27766. /**
  27767. * An event triggered before rendering the mesh
  27768. * @type {BABYLON.Observable}
  27769. */
  27770. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27771. /**
  27772. * An event triggered after rendering the mesh
  27773. * @type {BABYLON.Observable}
  27774. */
  27775. _this.onAfterRenderObservable = new BABYLON.Observable();
  27776. /**
  27777. * An event triggered before drawing the mesh
  27778. * @type {BABYLON.Observable}
  27779. */
  27780. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27781. // Members
  27782. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27783. _this.instances = new Array();
  27784. _this._LODLevels = new Array();
  27785. _this._visibleInstances = {};
  27786. _this._renderIdForInstances = new Array();
  27787. _this._batchCache = new _InstancesBatch();
  27788. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27789. // Use by builder only to know what orientation were the mesh build in.
  27790. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27791. _this.overrideMaterialSideOrientation = null;
  27792. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27793. // Will be used to save a source mesh reference, If any
  27794. _this._source = null;
  27795. scene = _this.getScene();
  27796. if (source) {
  27797. // Source mesh
  27798. _this._source = source;
  27799. // Geometry
  27800. if (source._geometry) {
  27801. source._geometry.applyToMesh(_this);
  27802. }
  27803. // Deep copy
  27804. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  27805. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  27806. // Metadata
  27807. if (source.metadata && source.metadata.clone) {
  27808. _this.metadata = source.metadata.clone();
  27809. }
  27810. else {
  27811. _this.metadata = source.metadata;
  27812. }
  27813. // Tags
  27814. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27815. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27816. }
  27817. // Parent
  27818. _this.parent = source.parent;
  27819. // Pivot
  27820. _this.setPivotMatrix(source.getPivotMatrix());
  27821. _this.id = name + "." + source.id;
  27822. // Material
  27823. _this.material = source.material;
  27824. var index;
  27825. if (!doNotCloneChildren) {
  27826. // Children
  27827. var directDescendants = source.getDescendants(true);
  27828. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27829. var child = directDescendants[index_1];
  27830. if (child.clone) {
  27831. child.clone(name + "." + child.name, _this);
  27832. }
  27833. }
  27834. }
  27835. // Physics clone
  27836. var physicsEngine = _this.getScene().getPhysicsEngine();
  27837. if (clonePhysicsImpostor && physicsEngine) {
  27838. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27839. if (impostor) {
  27840. _this.physicsImpostor = impostor.clone(_this);
  27841. }
  27842. }
  27843. // Particles
  27844. for (index = 0; index < scene.particleSystems.length; index++) {
  27845. var system = scene.particleSystems[index];
  27846. if (system.emitter === source) {
  27847. system.clone(system.name, _this);
  27848. }
  27849. }
  27850. _this.computeWorldMatrix(true);
  27851. }
  27852. // Parent
  27853. if (parent !== null) {
  27854. _this.parent = parent;
  27855. }
  27856. return _this;
  27857. }
  27858. Object.defineProperty(Mesh, "FRONTSIDE", {
  27859. /**
  27860. * Mesh side orientation : usually the external or front surface
  27861. */
  27862. get: function () {
  27863. return Mesh._FRONTSIDE;
  27864. },
  27865. enumerable: true,
  27866. configurable: true
  27867. });
  27868. Object.defineProperty(Mesh, "BACKSIDE", {
  27869. /**
  27870. * Mesh side orientation : usually the internal or back surface
  27871. */
  27872. get: function () {
  27873. return Mesh._BACKSIDE;
  27874. },
  27875. enumerable: true,
  27876. configurable: true
  27877. });
  27878. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27879. /**
  27880. * Mesh side orientation : both internal and external or front and back surfaces
  27881. */
  27882. get: function () {
  27883. return Mesh._DOUBLESIDE;
  27884. },
  27885. enumerable: true,
  27886. configurable: true
  27887. });
  27888. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27889. /**
  27890. * Mesh side orientation : by default, `FRONTSIDE`
  27891. */
  27892. get: function () {
  27893. return Mesh._DEFAULTSIDE;
  27894. },
  27895. enumerable: true,
  27896. configurable: true
  27897. });
  27898. Object.defineProperty(Mesh, "NO_CAP", {
  27899. /**
  27900. * Mesh cap setting : no cap
  27901. */
  27902. get: function () {
  27903. return Mesh._NO_CAP;
  27904. },
  27905. enumerable: true,
  27906. configurable: true
  27907. });
  27908. Object.defineProperty(Mesh, "CAP_START", {
  27909. /**
  27910. * Mesh cap setting : one cap at the beginning of the mesh
  27911. */
  27912. get: function () {
  27913. return Mesh._CAP_START;
  27914. },
  27915. enumerable: true,
  27916. configurable: true
  27917. });
  27918. Object.defineProperty(Mesh, "CAP_END", {
  27919. /**
  27920. * Mesh cap setting : one cap at the end of the mesh
  27921. */
  27922. get: function () {
  27923. return Mesh._CAP_END;
  27924. },
  27925. enumerable: true,
  27926. configurable: true
  27927. });
  27928. Object.defineProperty(Mesh, "CAP_ALL", {
  27929. /**
  27930. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27931. */
  27932. get: function () {
  27933. return Mesh._CAP_ALL;
  27934. },
  27935. enumerable: true,
  27936. configurable: true
  27937. });
  27938. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27939. set: function (callback) {
  27940. if (this._onBeforeDrawObserver) {
  27941. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27942. }
  27943. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27944. },
  27945. enumerable: true,
  27946. configurable: true
  27947. });
  27948. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27949. get: function () {
  27950. return this._morphTargetManager;
  27951. },
  27952. set: function (value) {
  27953. if (this._morphTargetManager === value) {
  27954. return;
  27955. }
  27956. this._morphTargetManager = value;
  27957. this._syncGeometryWithMorphTargetManager();
  27958. },
  27959. enumerable: true,
  27960. configurable: true
  27961. });
  27962. Object.defineProperty(Mesh.prototype, "source", {
  27963. get: function () {
  27964. return this._source;
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27970. get: function () {
  27971. return this._unIndexed;
  27972. },
  27973. set: function (value) {
  27974. if (this._unIndexed !== value) {
  27975. this._unIndexed = value;
  27976. this._markSubMeshesAsAttributesDirty();
  27977. }
  27978. },
  27979. enumerable: true,
  27980. configurable: true
  27981. });
  27982. // Methods
  27983. /**
  27984. * Returns the string "Mesh".
  27985. */
  27986. Mesh.prototype.getClassName = function () {
  27987. return "Mesh";
  27988. };
  27989. /**
  27990. * Returns a string.
  27991. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27992. */
  27993. Mesh.prototype.toString = function (fullDetails) {
  27994. var ret = _super.prototype.toString.call(this, fullDetails);
  27995. ret += ", n vertices: " + this.getTotalVertices();
  27996. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27997. if (this.animations) {
  27998. for (var i = 0; i < this.animations.length; i++) {
  27999. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  28000. }
  28001. }
  28002. if (fullDetails) {
  28003. if (this._geometry) {
  28004. var ib = this.getIndices();
  28005. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28006. if (vb && ib) {
  28007. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  28008. }
  28009. }
  28010. else {
  28011. ret += ", flat shading: UNKNOWN";
  28012. }
  28013. }
  28014. return ret;
  28015. };
  28016. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  28017. /**
  28018. * True if the mesh has some Levels Of Details (LOD).
  28019. * Returns a boolean.
  28020. */
  28021. get: function () {
  28022. return this._LODLevels.length > 0;
  28023. },
  28024. enumerable: true,
  28025. configurable: true
  28026. });
  28027. /**
  28028. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28029. * @returns an array of {BABYLON.MeshLODLevel}
  28030. */
  28031. Mesh.prototype.getLODLevels = function () {
  28032. return this._LODLevels;
  28033. };
  28034. Mesh.prototype._sortLODLevels = function () {
  28035. this._LODLevels.sort(function (a, b) {
  28036. if (a.distance < b.distance) {
  28037. return 1;
  28038. }
  28039. if (a.distance > b.distance) {
  28040. return -1;
  28041. }
  28042. return 0;
  28043. });
  28044. };
  28045. /**
  28046. * Add a mesh as LOD level triggered at the given distance.
  28047. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28048. * @param {number} distance The distance from the center of the object to show this level
  28049. * @param {Mesh} mesh The mesh to be added as LOD level
  28050. * @return {Mesh} This mesh (for chaining)
  28051. */
  28052. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28053. if (mesh && mesh._masterMesh) {
  28054. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28055. return this;
  28056. }
  28057. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28058. this._LODLevels.push(level);
  28059. if (mesh) {
  28060. mesh._masterMesh = this;
  28061. }
  28062. this._sortLODLevels();
  28063. return this;
  28064. };
  28065. /**
  28066. * Returns the LOD level mesh at the passed distance or null if not found.
  28067. * It is related to the method `addLODLevel(distance, mesh)`.
  28068. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28069. * Returns an object Mesh or `null`.
  28070. */
  28071. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28072. for (var index = 0; index < this._LODLevels.length; index++) {
  28073. var level = this._LODLevels[index];
  28074. if (level.distance === distance) {
  28075. return level.mesh;
  28076. }
  28077. }
  28078. return null;
  28079. };
  28080. /**
  28081. * Remove a mesh from the LOD array
  28082. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28083. * @param {Mesh} mesh The mesh to be removed.
  28084. * @return {Mesh} This mesh (for chaining)
  28085. */
  28086. Mesh.prototype.removeLODLevel = function (mesh) {
  28087. for (var index = 0; index < this._LODLevels.length; index++) {
  28088. if (this._LODLevels[index].mesh === mesh) {
  28089. this._LODLevels.splice(index, 1);
  28090. if (mesh) {
  28091. mesh._masterMesh = null;
  28092. }
  28093. }
  28094. }
  28095. this._sortLODLevels();
  28096. return this;
  28097. };
  28098. /**
  28099. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28101. */
  28102. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28103. if (!this._LODLevels || this._LODLevels.length === 0) {
  28104. return this;
  28105. }
  28106. var bSphere;
  28107. if (boundingSphere) {
  28108. bSphere = boundingSphere;
  28109. }
  28110. else {
  28111. var boundingInfo = this.getBoundingInfo();
  28112. bSphere = boundingInfo.boundingSphere;
  28113. }
  28114. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28115. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28116. if (this.onLODLevelSelection) {
  28117. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28118. }
  28119. return this;
  28120. }
  28121. for (var index = 0; index < this._LODLevels.length; index++) {
  28122. var level = this._LODLevels[index];
  28123. if (level.distance < distanceToCamera) {
  28124. if (level.mesh) {
  28125. level.mesh._preActivate();
  28126. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28127. }
  28128. if (this.onLODLevelSelection) {
  28129. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28130. }
  28131. return level.mesh;
  28132. }
  28133. }
  28134. if (this.onLODLevelSelection) {
  28135. this.onLODLevelSelection(distanceToCamera, this, this);
  28136. }
  28137. return this;
  28138. };
  28139. Object.defineProperty(Mesh.prototype, "geometry", {
  28140. /**
  28141. * Returns the mesh internal Geometry object.
  28142. */
  28143. get: function () {
  28144. return this._geometry;
  28145. },
  28146. enumerable: true,
  28147. configurable: true
  28148. });
  28149. /**
  28150. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28151. */
  28152. Mesh.prototype.getTotalVertices = function () {
  28153. if (this._geometry === null || this._geometry === undefined) {
  28154. return 0;
  28155. }
  28156. return this._geometry.getTotalVertices();
  28157. };
  28158. /**
  28159. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28160. * 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.
  28161. * You can force the copy with forceCopy === true
  28162. * Returns null if the mesh has no geometry or no vertex buffer.
  28163. * Possible `kind` values :
  28164. * - BABYLON.VertexBuffer.PositionKind
  28165. * - BABYLON.VertexBuffer.UVKind
  28166. * - BABYLON.VertexBuffer.UV2Kind
  28167. * - BABYLON.VertexBuffer.UV3Kind
  28168. * - BABYLON.VertexBuffer.UV4Kind
  28169. * - BABYLON.VertexBuffer.UV5Kind
  28170. * - BABYLON.VertexBuffer.UV6Kind
  28171. * - BABYLON.VertexBuffer.ColorKind
  28172. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28173. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28174. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28175. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28176. */
  28177. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28178. if (!this._geometry) {
  28179. return null;
  28180. }
  28181. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28182. };
  28183. /**
  28184. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28185. * Returns `null` if the mesh has no geometry.
  28186. * Possible `kind` values :
  28187. * - BABYLON.VertexBuffer.PositionKind
  28188. * - BABYLON.VertexBuffer.UVKind
  28189. * - BABYLON.VertexBuffer.UV2Kind
  28190. * - BABYLON.VertexBuffer.UV3Kind
  28191. * - BABYLON.VertexBuffer.UV4Kind
  28192. * - BABYLON.VertexBuffer.UV5Kind
  28193. * - BABYLON.VertexBuffer.UV6Kind
  28194. * - BABYLON.VertexBuffer.ColorKind
  28195. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28196. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28197. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28198. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28199. */
  28200. Mesh.prototype.getVertexBuffer = function (kind) {
  28201. if (!this._geometry) {
  28202. return null;
  28203. }
  28204. return this._geometry.getVertexBuffer(kind);
  28205. };
  28206. /**
  28207. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28208. * Possible `kind` values :
  28209. * - BABYLON.VertexBuffer.PositionKind
  28210. * - BABYLON.VertexBuffer.UVKind
  28211. * - BABYLON.VertexBuffer.UV2Kind
  28212. * - BABYLON.VertexBuffer.UV3Kind
  28213. * - BABYLON.VertexBuffer.UV4Kind
  28214. * - BABYLON.VertexBuffer.UV5Kind
  28215. * - BABYLON.VertexBuffer.UV6Kind
  28216. * - BABYLON.VertexBuffer.ColorKind
  28217. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28218. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28219. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28220. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28221. */
  28222. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28223. if (!this._geometry) {
  28224. if (this._delayInfo) {
  28225. return this._delayInfo.indexOf(kind) !== -1;
  28226. }
  28227. return false;
  28228. }
  28229. return this._geometry.isVerticesDataPresent(kind);
  28230. };
  28231. /**
  28232. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28233. * Possible `kind` values :
  28234. * - BABYLON.VertexBuffer.PositionKind
  28235. * - BABYLON.VertexBuffer.UVKind
  28236. * - BABYLON.VertexBuffer.UV2Kind
  28237. * - BABYLON.VertexBuffer.UV3Kind
  28238. * - BABYLON.VertexBuffer.UV4Kind
  28239. * - BABYLON.VertexBuffer.UV5Kind
  28240. * - BABYLON.VertexBuffer.UV6Kind
  28241. * - BABYLON.VertexBuffer.ColorKind
  28242. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28243. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28244. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28245. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28246. */
  28247. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28248. if (!this._geometry) {
  28249. if (this._delayInfo) {
  28250. return this._delayInfo.indexOf(kind) !== -1;
  28251. }
  28252. return false;
  28253. }
  28254. return this._geometry.isVertexBufferUpdatable(kind);
  28255. };
  28256. /**
  28257. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28258. * Possible `kind` values :
  28259. * - BABYLON.VertexBuffer.PositionKind
  28260. * - BABYLON.VertexBuffer.UVKind
  28261. * - BABYLON.VertexBuffer.UV2Kind
  28262. * - BABYLON.VertexBuffer.UV3Kind
  28263. * - BABYLON.VertexBuffer.UV4Kind
  28264. * - BABYLON.VertexBuffer.UV5Kind
  28265. * - BABYLON.VertexBuffer.UV6Kind
  28266. * - BABYLON.VertexBuffer.ColorKind
  28267. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28268. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28269. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28270. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28271. */
  28272. Mesh.prototype.getVerticesDataKinds = function () {
  28273. if (!this._geometry) {
  28274. var result = new Array();
  28275. if (this._delayInfo) {
  28276. this._delayInfo.forEach(function (kind, index, array) {
  28277. result.push(kind);
  28278. });
  28279. }
  28280. return result;
  28281. }
  28282. return this._geometry.getVerticesDataKinds();
  28283. };
  28284. /**
  28285. * Returns a positive integer : the total number of indices in this mesh geometry.
  28286. * Returns zero if the mesh has no geometry.
  28287. */
  28288. Mesh.prototype.getTotalIndices = function () {
  28289. if (!this._geometry) {
  28290. return 0;
  28291. }
  28292. return this._geometry.getTotalIndices();
  28293. };
  28294. /**
  28295. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28296. * 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.
  28297. * Returns an empty array if the mesh has no geometry.
  28298. */
  28299. Mesh.prototype.getIndices = function (copyWhenShared) {
  28300. if (!this._geometry) {
  28301. return [];
  28302. }
  28303. return this._geometry.getIndices(copyWhenShared);
  28304. };
  28305. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28306. get: function () {
  28307. return this._masterMesh !== null && this._masterMesh !== undefined;
  28308. },
  28309. enumerable: true,
  28310. configurable: true
  28311. });
  28312. /**
  28313. * Determine if the current mesh is ready to be rendered
  28314. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28315. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28316. * @returns true if all associated assets are ready (material, textures, shaders)
  28317. */
  28318. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28319. if (completeCheck === void 0) { completeCheck = false; }
  28320. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28321. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28322. return false;
  28323. }
  28324. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28325. return false;
  28326. }
  28327. if (!this.subMeshes || this.subMeshes.length === 0) {
  28328. return true;
  28329. }
  28330. if (!completeCheck) {
  28331. return true;
  28332. }
  28333. var engine = this.getEngine();
  28334. var scene = this.getScene();
  28335. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28336. this.computeWorldMatrix();
  28337. var mat = this.material || scene.defaultMaterial;
  28338. if (mat) {
  28339. if (mat.storeEffectOnSubMeshes) {
  28340. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28341. var subMesh = _a[_i];
  28342. var effectiveMaterial = subMesh.getMaterial();
  28343. if (effectiveMaterial) {
  28344. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28345. return false;
  28346. }
  28347. }
  28348. }
  28349. }
  28350. else {
  28351. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28352. return false;
  28353. }
  28354. }
  28355. }
  28356. // Shadows
  28357. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28358. var light = _c[_b];
  28359. var generator = light.getShadowGenerator();
  28360. if (generator) {
  28361. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28362. var subMesh = _e[_d];
  28363. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28364. return false;
  28365. }
  28366. }
  28367. }
  28368. }
  28369. // LOD
  28370. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28371. var lod = _g[_f];
  28372. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28373. return false;
  28374. }
  28375. }
  28376. return true;
  28377. };
  28378. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28379. /**
  28380. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28381. * This property is pertinent only for updatable parametric shapes.
  28382. */
  28383. get: function () {
  28384. return this._areNormalsFrozen;
  28385. },
  28386. enumerable: true,
  28387. configurable: true
  28388. });
  28389. /**
  28390. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28391. * It has no effect at all on other shapes.
  28392. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28393. * Returns the Mesh.
  28394. */
  28395. Mesh.prototype.freezeNormals = function () {
  28396. this._areNormalsFrozen = true;
  28397. return this;
  28398. };
  28399. /**
  28400. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28401. * It has no effect at all on other shapes.
  28402. * It reactivates the mesh normals computation if it was previously frozen.
  28403. * Returns the Mesh.
  28404. */
  28405. Mesh.prototype.unfreezeNormals = function () {
  28406. this._areNormalsFrozen = false;
  28407. return this;
  28408. };
  28409. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28410. /**
  28411. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28412. */
  28413. set: function (count) {
  28414. this._overridenInstanceCount = count;
  28415. },
  28416. enumerable: true,
  28417. configurable: true
  28418. });
  28419. // Methods
  28420. Mesh.prototype._preActivate = function () {
  28421. var sceneRenderId = this.getScene().getRenderId();
  28422. if (this._preActivateId === sceneRenderId) {
  28423. return this;
  28424. }
  28425. this._preActivateId = sceneRenderId;
  28426. this._visibleInstances = null;
  28427. return this;
  28428. };
  28429. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28430. if (this._visibleInstances) {
  28431. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28432. }
  28433. return this;
  28434. };
  28435. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28436. if (!this._visibleInstances) {
  28437. this._visibleInstances = {};
  28438. this._visibleInstances.defaultRenderId = renderId;
  28439. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28440. }
  28441. if (!this._visibleInstances[renderId]) {
  28442. this._visibleInstances[renderId] = new Array();
  28443. }
  28444. this._visibleInstances[renderId].push(instance);
  28445. return this;
  28446. };
  28447. /**
  28448. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28449. * This means the mesh underlying bounding box and sphere are recomputed.
  28450. * Returns the Mesh.
  28451. */
  28452. Mesh.prototype.refreshBoundingInfo = function () {
  28453. return this._refreshBoundingInfo(false);
  28454. };
  28455. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28456. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28457. return this;
  28458. }
  28459. var data = this._getPositionData(applySkeleton);
  28460. if (data) {
  28461. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28462. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28463. }
  28464. if (this.subMeshes) {
  28465. for (var index = 0; index < this.subMeshes.length; index++) {
  28466. this.subMeshes[index].refreshBoundingInfo();
  28467. }
  28468. }
  28469. this._updateBoundingInfo();
  28470. return this;
  28471. };
  28472. Mesh.prototype._getPositionData = function (applySkeleton) {
  28473. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28474. if (data && applySkeleton && this.skeleton) {
  28475. data = BABYLON.Tools.Slice(data);
  28476. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28477. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28478. if (matricesWeightsData && matricesIndicesData) {
  28479. var needExtras = this.numBoneInfluencers > 4;
  28480. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28481. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28482. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28483. var tempVector = BABYLON.Tmp.Vector3[0];
  28484. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28485. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28486. var matWeightIdx = 0;
  28487. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28488. finalMatrix.reset();
  28489. var inf;
  28490. var weight;
  28491. for (inf = 0; inf < 4; inf++) {
  28492. weight = matricesWeightsData[matWeightIdx + inf];
  28493. if (weight <= 0)
  28494. break;
  28495. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28496. finalMatrix.addToSelf(tempMatrix);
  28497. }
  28498. if (needExtras) {
  28499. for (inf = 0; inf < 4; inf++) {
  28500. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28501. if (weight <= 0)
  28502. break;
  28503. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28504. finalMatrix.addToSelf(tempMatrix);
  28505. }
  28506. }
  28507. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28508. tempVector.toArray(data, index);
  28509. }
  28510. }
  28511. }
  28512. return data;
  28513. };
  28514. Mesh.prototype._createGlobalSubMesh = function (force) {
  28515. var totalVertices = this.getTotalVertices();
  28516. if (!totalVertices || !this.getIndices()) {
  28517. return null;
  28518. }
  28519. // Check if we need to recreate the submeshes
  28520. if (this.subMeshes && this.subMeshes.length > 0) {
  28521. var ib = this.getIndices();
  28522. if (!ib) {
  28523. return null;
  28524. }
  28525. var totalIndices = ib.length;
  28526. var needToRecreate = false;
  28527. if (force) {
  28528. needToRecreate = true;
  28529. }
  28530. else {
  28531. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28532. var submesh = _a[_i];
  28533. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28534. needToRecreate = true;
  28535. break;
  28536. }
  28537. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28538. needToRecreate = true;
  28539. break;
  28540. }
  28541. }
  28542. }
  28543. if (!needToRecreate) {
  28544. return this.subMeshes[0];
  28545. }
  28546. }
  28547. this.releaseSubMeshes();
  28548. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28549. };
  28550. Mesh.prototype.subdivide = function (count) {
  28551. if (count < 1) {
  28552. return;
  28553. }
  28554. var totalIndices = this.getTotalIndices();
  28555. var subdivisionSize = (totalIndices / count) | 0;
  28556. var offset = 0;
  28557. // Ensure that subdivisionSize is a multiple of 3
  28558. while (subdivisionSize % 3 !== 0) {
  28559. subdivisionSize++;
  28560. }
  28561. this.releaseSubMeshes();
  28562. for (var index = 0; index < count; index++) {
  28563. if (offset >= totalIndices) {
  28564. break;
  28565. }
  28566. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28567. offset += subdivisionSize;
  28568. }
  28569. this.synchronizeInstances();
  28570. };
  28571. /**
  28572. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28573. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28574. * The `data` are either a numeric array either a Float32Array.
  28575. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28576. * 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).
  28577. * Note that a new underlying VertexBuffer object is created each call.
  28578. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28579. *
  28580. * Possible `kind` values :
  28581. * - BABYLON.VertexBuffer.PositionKind
  28582. * - BABYLON.VertexBuffer.UVKind
  28583. * - BABYLON.VertexBuffer.UV2Kind
  28584. * - BABYLON.VertexBuffer.UV3Kind
  28585. * - BABYLON.VertexBuffer.UV4Kind
  28586. * - BABYLON.VertexBuffer.UV5Kind
  28587. * - BABYLON.VertexBuffer.UV6Kind
  28588. * - BABYLON.VertexBuffer.ColorKind
  28589. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28590. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28591. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28592. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28593. *
  28594. * Returns the Mesh.
  28595. */
  28596. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28597. if (updatable === void 0) { updatable = false; }
  28598. if (!this._geometry) {
  28599. var vertexData = new BABYLON.VertexData();
  28600. vertexData.set(data, kind);
  28601. var scene = this.getScene();
  28602. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28603. }
  28604. else {
  28605. this._geometry.setVerticesData(kind, data, updatable, stride);
  28606. }
  28607. return this;
  28608. };
  28609. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28610. if (updatable === void 0) { updatable = true; }
  28611. var vb = this.getVertexBuffer(kind);
  28612. if (!vb || vb.isUpdatable() === updatable) {
  28613. return;
  28614. }
  28615. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28616. };
  28617. /**
  28618. * Sets the mesh VertexBuffer.
  28619. * Returns the Mesh.
  28620. */
  28621. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28622. if (!this._geometry) {
  28623. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28624. }
  28625. this._geometry.setVerticesBuffer(buffer);
  28626. return this;
  28627. };
  28628. /**
  28629. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28630. * If the mesh has no geometry, it is simply returned as it is.
  28631. * The `data` are either a numeric array either a Float32Array.
  28632. * No new underlying VertexBuffer object is created.
  28633. * 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.
  28634. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28635. *
  28636. * Possible `kind` values :
  28637. * - BABYLON.VertexBuffer.PositionKind
  28638. * - BABYLON.VertexBuffer.UVKind
  28639. * - BABYLON.VertexBuffer.UV2Kind
  28640. * - BABYLON.VertexBuffer.UV3Kind
  28641. * - BABYLON.VertexBuffer.UV4Kind
  28642. * - BABYLON.VertexBuffer.UV5Kind
  28643. * - BABYLON.VertexBuffer.UV6Kind
  28644. * - BABYLON.VertexBuffer.ColorKind
  28645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28649. *
  28650. * Returns the Mesh.
  28651. */
  28652. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28653. if (!this._geometry) {
  28654. return this;
  28655. }
  28656. if (!makeItUnique) {
  28657. this._geometry.updateVerticesData(kind, data, updateExtends);
  28658. }
  28659. else {
  28660. this.makeGeometryUnique();
  28661. this.updateVerticesData(kind, data, updateExtends, false);
  28662. }
  28663. return this;
  28664. };
  28665. /**
  28666. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28667. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28668. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28669. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28670. * Returns the Mesh.
  28671. */
  28672. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28673. if (computeNormals === void 0) { computeNormals = true; }
  28674. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28675. if (!positions) {
  28676. return this;
  28677. }
  28678. positionFunction(positions);
  28679. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28680. if (computeNormals) {
  28681. var indices = this.getIndices();
  28682. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28683. if (!normals) {
  28684. return this;
  28685. }
  28686. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28687. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28688. }
  28689. return this;
  28690. };
  28691. /**
  28692. * Creates a un-shared specific occurence of the geometry for the mesh.
  28693. * Returns the Mesh.
  28694. */
  28695. Mesh.prototype.makeGeometryUnique = function () {
  28696. if (!this._geometry) {
  28697. return this;
  28698. }
  28699. var oldGeometry = this._geometry;
  28700. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28701. oldGeometry.releaseForMesh(this, true);
  28702. geometry.applyToMesh(this);
  28703. return this;
  28704. };
  28705. /**
  28706. * Sets the mesh indices.
  28707. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28708. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28709. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28710. * This method creates a new index buffer each call.
  28711. * Returns the Mesh.
  28712. */
  28713. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28714. if (totalVertices === void 0) { totalVertices = null; }
  28715. if (updatable === void 0) { updatable = false; }
  28716. if (!this._geometry) {
  28717. var vertexData = new BABYLON.VertexData();
  28718. vertexData.indices = indices;
  28719. var scene = this.getScene();
  28720. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28721. }
  28722. else {
  28723. this._geometry.setIndices(indices, totalVertices, updatable);
  28724. }
  28725. return this;
  28726. };
  28727. /**
  28728. * Update the current index buffer
  28729. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28730. * Returns the Mesh.
  28731. */
  28732. Mesh.prototype.updateIndices = function (indices, offset) {
  28733. if (!this._geometry) {
  28734. return this;
  28735. }
  28736. this._geometry.updateIndices(indices, offset);
  28737. return this;
  28738. };
  28739. /**
  28740. * Invert the geometry to move from a right handed system to a left handed one.
  28741. * Returns the Mesh.
  28742. */
  28743. Mesh.prototype.toLeftHanded = function () {
  28744. if (!this._geometry) {
  28745. return this;
  28746. }
  28747. this._geometry.toLeftHanded();
  28748. return this;
  28749. };
  28750. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28751. if (!this._geometry) {
  28752. return this;
  28753. }
  28754. var engine = this.getScene().getEngine();
  28755. // Wireframe
  28756. var indexToBind;
  28757. if (this._unIndexed) {
  28758. indexToBind = null;
  28759. }
  28760. else {
  28761. switch (fillMode) {
  28762. case BABYLON.Material.PointFillMode:
  28763. indexToBind = null;
  28764. break;
  28765. case BABYLON.Material.WireFrameFillMode:
  28766. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28767. break;
  28768. default:
  28769. case BABYLON.Material.TriangleFillMode:
  28770. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28771. break;
  28772. }
  28773. }
  28774. // VBOs
  28775. this._geometry._bind(effect, indexToBind);
  28776. return this;
  28777. };
  28778. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28779. if (alternate === void 0) { alternate = false; }
  28780. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28781. return this;
  28782. }
  28783. this.onBeforeDrawObservable.notifyObservers(this);
  28784. var scene = this.getScene();
  28785. var engine = scene.getEngine();
  28786. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28787. // or triangles as points
  28788. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28789. }
  28790. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28791. // Triangles as wireframe
  28792. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28793. }
  28794. else {
  28795. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28796. }
  28797. if (scene._isAlternateRenderingEnabled && !alternate) {
  28798. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28799. if (!effect || !scene.activeCamera) {
  28800. return this;
  28801. }
  28802. scene._switchToAlternateCameraConfiguration(true);
  28803. this._effectiveMaterial.bindView(effect);
  28804. this._effectiveMaterial.bindViewProjection(effect);
  28805. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28806. this._draw(subMesh, fillMode, instancesCount, true);
  28807. engine.setViewport(scene.activeCamera.viewport);
  28808. scene._switchToAlternateCameraConfiguration(false);
  28809. this._effectiveMaterial.bindView(effect);
  28810. this._effectiveMaterial.bindViewProjection(effect);
  28811. }
  28812. return this;
  28813. };
  28814. /**
  28815. * Registers for this mesh a javascript function called just before the rendering process.
  28816. * This function is passed the current mesh.
  28817. * Return the Mesh.
  28818. */
  28819. Mesh.prototype.registerBeforeRender = function (func) {
  28820. this.onBeforeRenderObservable.add(func);
  28821. return this;
  28822. };
  28823. /**
  28824. * Disposes a previously registered javascript function called before the rendering.
  28825. * This function is passed the current mesh.
  28826. * Returns the Mesh.
  28827. */
  28828. Mesh.prototype.unregisterBeforeRender = function (func) {
  28829. this.onBeforeRenderObservable.removeCallback(func);
  28830. return this;
  28831. };
  28832. /**
  28833. * Registers for this mesh a javascript function called just after the rendering is complete.
  28834. * This function is passed the current mesh.
  28835. * Returns the Mesh.
  28836. */
  28837. Mesh.prototype.registerAfterRender = function (func) {
  28838. this.onAfterRenderObservable.add(func);
  28839. return this;
  28840. };
  28841. /**
  28842. * Disposes a previously registered javascript function called after the rendering.
  28843. * This function is passed the current mesh.
  28844. * Return the Mesh.
  28845. */
  28846. Mesh.prototype.unregisterAfterRender = function (func) {
  28847. this.onAfterRenderObservable.removeCallback(func);
  28848. return this;
  28849. };
  28850. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28851. var scene = this.getScene();
  28852. this._batchCache.mustReturn = false;
  28853. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28854. this._batchCache.visibleInstances[subMeshId] = null;
  28855. if (this._visibleInstances) {
  28856. var currentRenderId = scene.getRenderId();
  28857. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28858. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28859. var selfRenderId = this._renderId;
  28860. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28861. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28862. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28863. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28864. }
  28865. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28866. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28867. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28868. this._batchCache.mustReturn = true;
  28869. return this._batchCache;
  28870. }
  28871. if (currentRenderId !== selfRenderId) {
  28872. this._batchCache.renderSelf[subMeshId] = false;
  28873. }
  28874. }
  28875. this._renderIdForInstances[subMeshId] = currentRenderId;
  28876. }
  28877. return this._batchCache;
  28878. };
  28879. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28880. var visibleInstances = batch.visibleInstances[subMesh._id];
  28881. if (!visibleInstances) {
  28882. return this;
  28883. }
  28884. var matricesCount = visibleInstances.length + 1;
  28885. var bufferSize = matricesCount * 16 * 4;
  28886. var currentInstancesBufferSize = this._instancesBufferSize;
  28887. var instancesBuffer = this._instancesBuffer;
  28888. while (this._instancesBufferSize < bufferSize) {
  28889. this._instancesBufferSize *= 2;
  28890. }
  28891. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28892. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28893. }
  28894. var offset = 0;
  28895. var instancesCount = 0;
  28896. var world = this.getWorldMatrix();
  28897. if (batch.renderSelf[subMesh._id]) {
  28898. world.copyToArray(this._instancesData, offset);
  28899. offset += 16;
  28900. instancesCount++;
  28901. }
  28902. if (visibleInstances) {
  28903. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28904. var instance = visibleInstances[instanceIndex];
  28905. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28906. offset += 16;
  28907. instancesCount++;
  28908. }
  28909. }
  28910. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28911. if (instancesBuffer) {
  28912. instancesBuffer.dispose();
  28913. }
  28914. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28915. this._instancesBuffer = instancesBuffer;
  28916. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28917. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28918. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28919. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28920. }
  28921. else {
  28922. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28923. }
  28924. this._bind(subMesh, effect, fillMode);
  28925. this._draw(subMesh, fillMode, instancesCount);
  28926. engine.unbindInstanceAttributes();
  28927. return this;
  28928. };
  28929. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28930. var scene = this.getScene();
  28931. var engine = scene.getEngine();
  28932. if (hardwareInstancedRendering) {
  28933. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28934. }
  28935. else {
  28936. if (batch.renderSelf[subMesh._id]) {
  28937. // Draw
  28938. if (onBeforeDraw) {
  28939. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28940. }
  28941. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28942. }
  28943. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28944. if (visibleInstancesForSubMesh) {
  28945. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28946. var instance = visibleInstancesForSubMesh[instanceIndex];
  28947. // World
  28948. var world = instance.getWorldMatrix();
  28949. if (onBeforeDraw) {
  28950. onBeforeDraw(true, world, effectiveMaterial);
  28951. }
  28952. // Draw
  28953. this._draw(subMesh, fillMode);
  28954. }
  28955. }
  28956. }
  28957. return this;
  28958. };
  28959. /**
  28960. * Triggers the draw call for the mesh.
  28961. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28962. * Returns the Mesh.
  28963. */
  28964. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28965. this.checkOcclusionQuery();
  28966. if (this._isOccluded) {
  28967. return this;
  28968. }
  28969. var scene = this.getScene();
  28970. // Managing instances
  28971. var batch = this._getInstancesRenderList(subMesh._id);
  28972. if (batch.mustReturn) {
  28973. return this;
  28974. }
  28975. // Checking geometry state
  28976. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28977. return this;
  28978. }
  28979. this.onBeforeRenderObservable.notifyObservers(this);
  28980. var engine = scene.getEngine();
  28981. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28982. // Material
  28983. var material = subMesh.getMaterial();
  28984. if (!material) {
  28985. return this;
  28986. }
  28987. this._effectiveMaterial = material;
  28988. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28989. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28990. return this;
  28991. }
  28992. }
  28993. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28994. return this;
  28995. }
  28996. // Alpha mode
  28997. if (enableAlphaMode) {
  28998. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28999. }
  29000. // Outline - step 1
  29001. var savedDepthWrite = engine.getDepthWrite();
  29002. if (this.renderOutline) {
  29003. engine.setDepthWrite(false);
  29004. scene.getOutlineRenderer().render(subMesh, batch);
  29005. engine.setDepthWrite(savedDepthWrite);
  29006. }
  29007. var effect;
  29008. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29009. effect = subMesh.effect;
  29010. }
  29011. else {
  29012. effect = this._effectiveMaterial.getEffect();
  29013. }
  29014. if (!effect) {
  29015. return this;
  29016. }
  29017. var sideOrientation = this.overrideMaterialSideOrientation;
  29018. if (sideOrientation == null) {
  29019. sideOrientation = this._effectiveMaterial.sideOrientation;
  29020. if (this._getWorldMatrixDeterminant() < 0) {
  29021. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29022. }
  29023. }
  29024. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29025. if (this._effectiveMaterial.forceDepthWrite) {
  29026. engine.setDepthWrite(true);
  29027. }
  29028. // Bind
  29029. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29030. if (!hardwareInstancedRendering) {
  29031. this._bind(subMesh, effect, fillMode);
  29032. }
  29033. var world = this.getWorldMatrix();
  29034. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29035. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29036. }
  29037. else {
  29038. this._effectiveMaterial.bind(world, this);
  29039. }
  29040. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29041. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29042. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29043. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29044. }
  29045. // Draw
  29046. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29047. // Unbind
  29048. this._effectiveMaterial.unbind();
  29049. // Outline - step 2
  29050. if (this.renderOutline && savedDepthWrite) {
  29051. engine.setDepthWrite(true);
  29052. engine.setColorWrite(false);
  29053. scene.getOutlineRenderer().render(subMesh, batch);
  29054. engine.setColorWrite(true);
  29055. }
  29056. // Overlay
  29057. if (this.renderOverlay) {
  29058. var currentMode = engine.getAlphaMode();
  29059. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29060. scene.getOutlineRenderer().render(subMesh, batch, true);
  29061. engine.setAlphaMode(currentMode);
  29062. }
  29063. this.onAfterRenderObservable.notifyObservers(this);
  29064. return this;
  29065. };
  29066. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29067. if (isInstance && effectiveMaterial) {
  29068. effectiveMaterial.bindOnlyWorldMatrix(world);
  29069. }
  29070. };
  29071. /**
  29072. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29073. */
  29074. Mesh.prototype.getEmittedParticleSystems = function () {
  29075. var results = new Array();
  29076. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29077. var particleSystem = this.getScene().particleSystems[index];
  29078. if (particleSystem.emitter === this) {
  29079. results.push(particleSystem);
  29080. }
  29081. }
  29082. return results;
  29083. };
  29084. /**
  29085. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29086. */
  29087. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29088. var results = new Array();
  29089. var descendants = this.getDescendants();
  29090. descendants.push(this);
  29091. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29092. var particleSystem = this.getScene().particleSystems[index];
  29093. var emitter = particleSystem.emitter;
  29094. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29095. results.push(particleSystem);
  29096. }
  29097. }
  29098. return results;
  29099. };
  29100. Mesh.prototype._checkDelayState = function () {
  29101. var scene = this.getScene();
  29102. if (this._geometry) {
  29103. this._geometry.load(scene);
  29104. }
  29105. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29107. this._queueLoad(scene);
  29108. }
  29109. return this;
  29110. };
  29111. Mesh.prototype._queueLoad = function (scene) {
  29112. var _this = this;
  29113. scene._addPendingData(this);
  29114. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29115. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29116. if (data instanceof ArrayBuffer) {
  29117. _this._delayLoadingFunction(data, _this);
  29118. }
  29119. else {
  29120. _this._delayLoadingFunction(JSON.parse(data), _this);
  29121. }
  29122. _this.instances.forEach(function (instance) {
  29123. instance._syncSubMeshes();
  29124. });
  29125. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29126. scene._removePendingData(_this);
  29127. }, function () { }, scene.database, getBinaryData);
  29128. return this;
  29129. };
  29130. /**
  29131. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29132. */
  29133. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29134. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29135. return false;
  29136. }
  29137. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29138. return false;
  29139. }
  29140. this._checkDelayState();
  29141. return true;
  29142. };
  29143. /**
  29144. * Sets the mesh material by the material or multiMaterial `id` property.
  29145. * The material `id` is a string identifying the material or the multiMaterial.
  29146. * This method returns the Mesh.
  29147. */
  29148. Mesh.prototype.setMaterialByID = function (id) {
  29149. var materials = this.getScene().materials;
  29150. var index;
  29151. for (index = materials.length - 1; index > -1; index--) {
  29152. if (materials[index].id === id) {
  29153. this.material = materials[index];
  29154. return this;
  29155. }
  29156. }
  29157. // Multi
  29158. var multiMaterials = this.getScene().multiMaterials;
  29159. for (index = multiMaterials.length - 1; index > -1; index--) {
  29160. if (multiMaterials[index].id === id) {
  29161. this.material = multiMaterials[index];
  29162. return this;
  29163. }
  29164. }
  29165. return this;
  29166. };
  29167. /**
  29168. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29169. */
  29170. Mesh.prototype.getAnimatables = function () {
  29171. var results = new Array();
  29172. if (this.material) {
  29173. results.push(this.material);
  29174. }
  29175. if (this.skeleton) {
  29176. results.push(this.skeleton);
  29177. }
  29178. return results;
  29179. };
  29180. /**
  29181. * Modifies the mesh geometry according to the passed transformation matrix.
  29182. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29183. * The mesh normals are modified accordingly the same transformation.
  29184. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29185. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29186. * Returns the Mesh.
  29187. */
  29188. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29189. // Position
  29190. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29191. return this;
  29192. }
  29193. var submeshes = this.subMeshes.splice(0);
  29194. this._resetPointsArrayCache();
  29195. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29196. var temp = new Array();
  29197. var index;
  29198. for (index = 0; index < data.length; index += 3) {
  29199. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29200. }
  29201. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29202. // Normals
  29203. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29204. return this;
  29205. }
  29206. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29207. temp = [];
  29208. for (index = 0; index < data.length; index += 3) {
  29209. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29210. }
  29211. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29212. // flip faces?
  29213. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29214. this.flipFaces();
  29215. }
  29216. // Restore submeshes
  29217. this.releaseSubMeshes();
  29218. this.subMeshes = submeshes;
  29219. return this;
  29220. };
  29221. /**
  29222. * Modifies the mesh geometry according to its own current World Matrix.
  29223. * The mesh World Matrix is then reset.
  29224. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29225. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29226. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29227. * Returns the Mesh.
  29228. */
  29229. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29230. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29231. this.scaling.copyFromFloats(1, 1, 1);
  29232. this.position.copyFromFloats(0, 0, 0);
  29233. this.rotation.copyFromFloats(0, 0, 0);
  29234. //only if quaternion is already set
  29235. if (this.rotationQuaternion) {
  29236. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29237. }
  29238. this._worldMatrix = BABYLON.Matrix.Identity();
  29239. return this;
  29240. };
  29241. Object.defineProperty(Mesh.prototype, "_positions", {
  29242. // Cache
  29243. get: function () {
  29244. if (this._geometry) {
  29245. return this._geometry._positions;
  29246. }
  29247. return null;
  29248. },
  29249. enumerable: true,
  29250. configurable: true
  29251. });
  29252. Mesh.prototype._resetPointsArrayCache = function () {
  29253. if (this._geometry) {
  29254. this._geometry._resetPointsArrayCache();
  29255. }
  29256. return this;
  29257. };
  29258. Mesh.prototype._generatePointsArray = function () {
  29259. if (this._geometry) {
  29260. return this._geometry._generatePointsArray();
  29261. }
  29262. return false;
  29263. };
  29264. /**
  29265. * Returns a new Mesh object generated from the current mesh properties.
  29266. * This method must not get confused with createInstance().
  29267. * The parameter `name` is a string, the name given to the new mesh.
  29268. * The optional parameter `newParent` can be any Node object (default `null`).
  29269. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29270. * 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.
  29271. */
  29272. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29273. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29274. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29275. };
  29276. /**
  29277. * Releases resources associated with this mesh.
  29278. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29279. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29280. */
  29281. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29282. var _this = this;
  29283. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29284. this.morphTargetManager = null;
  29285. if (this._geometry) {
  29286. this._geometry.releaseForMesh(this, true);
  29287. }
  29288. // Sources
  29289. var meshes = this.getScene().meshes;
  29290. meshes.forEach(function (abstractMesh) {
  29291. var mesh = abstractMesh;
  29292. if (mesh._source && mesh._source === _this) {
  29293. mesh._source = null;
  29294. }
  29295. });
  29296. this._source = null;
  29297. // Instances
  29298. if (this._instancesBuffer) {
  29299. this._instancesBuffer.dispose();
  29300. this._instancesBuffer = null;
  29301. }
  29302. while (this.instances.length) {
  29303. this.instances[0].dispose();
  29304. }
  29305. // Effect layers.
  29306. var effectLayers = this.getScene().effectLayers;
  29307. for (var i = 0; i < effectLayers.length; i++) {
  29308. var effectLayer = effectLayers[i];
  29309. if (effectLayer) {
  29310. effectLayer._disposeMesh(this);
  29311. }
  29312. }
  29313. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29314. };
  29315. /**
  29316. * Modifies the mesh geometry according to a displacement map.
  29317. * 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.
  29318. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29319. * This method returns nothing.
  29320. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29321. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29322. * 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.
  29323. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29324. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29325. *
  29326. * Returns the Mesh.
  29327. */
  29328. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29329. var _this = this;
  29330. var scene = this.getScene();
  29331. var onload = function (img) {
  29332. // Getting height map data
  29333. var canvas = document.createElement("canvas");
  29334. var context = canvas.getContext("2d");
  29335. var heightMapWidth = img.width;
  29336. var heightMapHeight = img.height;
  29337. canvas.width = heightMapWidth;
  29338. canvas.height = heightMapHeight;
  29339. context.drawImage(img, 0, 0);
  29340. // Create VertexData from map data
  29341. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29342. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29343. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29344. //execute success callback, if set
  29345. if (onSuccess) {
  29346. onSuccess(_this);
  29347. }
  29348. };
  29349. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29350. return this;
  29351. };
  29352. /**
  29353. * Modifies the mesh geometry according to a displacementMap buffer.
  29354. * 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.
  29355. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29356. * This method returns nothing.
  29357. * 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.
  29358. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29359. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29360. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29361. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29362. *
  29363. * Returns the Mesh.
  29364. */
  29365. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29366. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29367. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29368. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29369. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29370. return this;
  29371. }
  29372. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29373. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29374. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29375. var position = BABYLON.Vector3.Zero();
  29376. var normal = BABYLON.Vector3.Zero();
  29377. var uv = BABYLON.Vector2.Zero();
  29378. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29379. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29380. for (var index = 0; index < positions.length; index += 3) {
  29381. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29382. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29383. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29384. // Compute height
  29385. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29386. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29387. var pos = (u + v * heightMapWidth) * 4;
  29388. var r = buffer[pos] / 255.0;
  29389. var g = buffer[pos + 1] / 255.0;
  29390. var b = buffer[pos + 2] / 255.0;
  29391. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29392. normal.normalize();
  29393. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29394. position = position.add(normal);
  29395. position.toArray(positions, index);
  29396. }
  29397. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29398. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29399. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29400. return this;
  29401. };
  29402. /**
  29403. * Modify the mesh to get a flat shading rendering.
  29404. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29405. * This method returns the Mesh.
  29406. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29407. */
  29408. Mesh.prototype.convertToFlatShadedMesh = function () {
  29409. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29410. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29411. var kinds = this.getVerticesDataKinds();
  29412. var vbs = {};
  29413. var data = {};
  29414. var newdata = {};
  29415. var updatableNormals = false;
  29416. var kindIndex;
  29417. var kind;
  29418. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29419. kind = kinds[kindIndex];
  29420. var vertexBuffer = this.getVertexBuffer(kind);
  29421. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29422. updatableNormals = vertexBuffer.isUpdatable();
  29423. kinds.splice(kindIndex, 1);
  29424. kindIndex--;
  29425. continue;
  29426. }
  29427. vbs[kind] = vertexBuffer;
  29428. data[kind] = vbs[kind].getData();
  29429. newdata[kind] = [];
  29430. }
  29431. // Save previous submeshes
  29432. var previousSubmeshes = this.subMeshes.slice(0);
  29433. var indices = this.getIndices();
  29434. var totalIndices = this.getTotalIndices();
  29435. // Generating unique vertices per face
  29436. var index;
  29437. for (index = 0; index < totalIndices; index++) {
  29438. var vertexIndex = indices[index];
  29439. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29440. kind = kinds[kindIndex];
  29441. var stride = vbs[kind].getStrideSize();
  29442. for (var offset = 0; offset < stride; offset++) {
  29443. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29444. }
  29445. }
  29446. }
  29447. // Updating faces & normal
  29448. var normals = [];
  29449. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29450. for (index = 0; index < totalIndices; index += 3) {
  29451. indices[index] = index;
  29452. indices[index + 1] = index + 1;
  29453. indices[index + 2] = index + 2;
  29454. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29455. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29456. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29457. var p1p2 = p1.subtract(p2);
  29458. var p3p2 = p3.subtract(p2);
  29459. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29460. // Store same normals for every vertex
  29461. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29462. normals.push(normal.x);
  29463. normals.push(normal.y);
  29464. normals.push(normal.z);
  29465. }
  29466. }
  29467. this.setIndices(indices);
  29468. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29469. // Updating vertex buffers
  29470. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29471. kind = kinds[kindIndex];
  29472. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29473. }
  29474. // Updating submeshes
  29475. this.releaseSubMeshes();
  29476. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29477. var previousOne = previousSubmeshes[submeshIndex];
  29478. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29479. }
  29480. this.synchronizeInstances();
  29481. return this;
  29482. };
  29483. /**
  29484. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29485. * In other words, more vertices, no more indices and a single bigger VBO.
  29486. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29487. * Returns the Mesh.
  29488. */
  29489. Mesh.prototype.convertToUnIndexedMesh = function () {
  29490. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29491. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29492. var kinds = this.getVerticesDataKinds();
  29493. var vbs = {};
  29494. var data = {};
  29495. var newdata = {};
  29496. var kindIndex;
  29497. var kind;
  29498. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29499. kind = kinds[kindIndex];
  29500. var vertexBuffer = this.getVertexBuffer(kind);
  29501. vbs[kind] = vertexBuffer;
  29502. data[kind] = vbs[kind].getData();
  29503. newdata[kind] = [];
  29504. }
  29505. // Save previous submeshes
  29506. var previousSubmeshes = this.subMeshes.slice(0);
  29507. var indices = this.getIndices();
  29508. var totalIndices = this.getTotalIndices();
  29509. // Generating unique vertices per face
  29510. var index;
  29511. for (index = 0; index < totalIndices; index++) {
  29512. var vertexIndex = indices[index];
  29513. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29514. kind = kinds[kindIndex];
  29515. var stride = vbs[kind].getStrideSize();
  29516. for (var offset = 0; offset < stride; offset++) {
  29517. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29518. }
  29519. }
  29520. }
  29521. // Updating indices
  29522. for (index = 0; index < totalIndices; index += 3) {
  29523. indices[index] = index;
  29524. indices[index + 1] = index + 1;
  29525. indices[index + 2] = index + 2;
  29526. }
  29527. this.setIndices(indices);
  29528. // Updating vertex buffers
  29529. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29530. kind = kinds[kindIndex];
  29531. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29532. }
  29533. // Updating submeshes
  29534. this.releaseSubMeshes();
  29535. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29536. var previousOne = previousSubmeshes[submeshIndex];
  29537. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29538. }
  29539. this._unIndexed = true;
  29540. this.synchronizeInstances();
  29541. return this;
  29542. };
  29543. /**
  29544. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29545. * This method returns the Mesh.
  29546. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29547. */
  29548. Mesh.prototype.flipFaces = function (flipNormals) {
  29549. if (flipNormals === void 0) { flipNormals = false; }
  29550. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29551. var i;
  29552. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29553. for (i = 0; i < vertex_data.normals.length; i++) {
  29554. vertex_data.normals[i] *= -1;
  29555. }
  29556. }
  29557. if (vertex_data.indices) {
  29558. var temp;
  29559. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29560. // reassign indices
  29561. temp = vertex_data.indices[i + 1];
  29562. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29563. vertex_data.indices[i + 2] = temp;
  29564. }
  29565. }
  29566. vertex_data.applyToMesh(this);
  29567. return this;
  29568. };
  29569. // Instances
  29570. /**
  29571. * Creates a new InstancedMesh object from the mesh model.
  29572. * An instance shares the same properties and the same material than its model.
  29573. * Only these properties of each instance can then be set individually :
  29574. * - position
  29575. * - rotation
  29576. * - rotationQuaternion
  29577. * - setPivotMatrix
  29578. * - scaling
  29579. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29580. * Warning : this method is not supported for Line mesh and LineSystem
  29581. */
  29582. Mesh.prototype.createInstance = function (name) {
  29583. return new BABYLON.InstancedMesh(name, this);
  29584. };
  29585. /**
  29586. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29587. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29588. * This method returns the Mesh.
  29589. */
  29590. Mesh.prototype.synchronizeInstances = function () {
  29591. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29592. var instance = this.instances[instanceIndex];
  29593. instance._syncSubMeshes();
  29594. }
  29595. return this;
  29596. };
  29597. /**
  29598. * Simplify the mesh according to the given array of settings.
  29599. * Function will return immediately and will simplify async. It returns the Mesh.
  29600. * @param settings a collection of simplification settings.
  29601. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29602. * @param type the type of simplification to run.
  29603. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29604. */
  29605. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29606. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29607. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29608. this.getScene().simplificationQueue.addTask({
  29609. settings: settings,
  29610. parallelProcessing: parallelProcessing,
  29611. mesh: this,
  29612. simplificationType: simplificationType,
  29613. successCallback: successCallback
  29614. });
  29615. return this;
  29616. };
  29617. /**
  29618. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29619. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29620. * This should be used together with the simplification to avoid disappearing triangles.
  29621. * Returns the Mesh.
  29622. * @param successCallback an optional success callback to be called after the optimization finished.
  29623. */
  29624. Mesh.prototype.optimizeIndices = function (successCallback) {
  29625. var _this = this;
  29626. var indices = this.getIndices();
  29627. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29628. if (!positions || !indices) {
  29629. return this;
  29630. }
  29631. var vectorPositions = new Array();
  29632. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29633. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29634. }
  29635. var dupes = new Array();
  29636. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29637. var realPos = vectorPositions.length - 1 - iteration;
  29638. var testedPosition = vectorPositions[realPos];
  29639. for (var j = 0; j < realPos; ++j) {
  29640. var againstPosition = vectorPositions[j];
  29641. if (testedPosition.equals(againstPosition)) {
  29642. dupes[realPos] = j;
  29643. break;
  29644. }
  29645. }
  29646. }, function () {
  29647. for (var i = 0; i < indices.length; ++i) {
  29648. indices[i] = dupes[indices[i]] || indices[i];
  29649. }
  29650. //indices are now reordered
  29651. var originalSubMeshes = _this.subMeshes.slice(0);
  29652. _this.setIndices(indices);
  29653. _this.subMeshes = originalSubMeshes;
  29654. if (successCallback) {
  29655. successCallback(_this);
  29656. }
  29657. });
  29658. return this;
  29659. };
  29660. Mesh.prototype.serialize = function (serializationObject) {
  29661. serializationObject.name = this.name;
  29662. serializationObject.id = this.id;
  29663. serializationObject.type = this.getClassName();
  29664. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29665. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29666. }
  29667. serializationObject.position = this.position.asArray();
  29668. if (this.rotationQuaternion) {
  29669. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29670. }
  29671. else if (this.rotation) {
  29672. serializationObject.rotation = this.rotation.asArray();
  29673. }
  29674. serializationObject.scaling = this.scaling.asArray();
  29675. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29676. serializationObject.isEnabled = this.isEnabled(false);
  29677. serializationObject.isVisible = this.isVisible;
  29678. serializationObject.infiniteDistance = this.infiniteDistance;
  29679. serializationObject.pickable = this.isPickable;
  29680. serializationObject.receiveShadows = this.receiveShadows;
  29681. serializationObject.billboardMode = this.billboardMode;
  29682. serializationObject.visibility = this.visibility;
  29683. serializationObject.checkCollisions = this.checkCollisions;
  29684. serializationObject.isBlocker = this.isBlocker;
  29685. // Parent
  29686. if (this.parent) {
  29687. serializationObject.parentId = this.parent.id;
  29688. }
  29689. // Geometry
  29690. serializationObject.isUnIndexed = this.isUnIndexed;
  29691. var geometry = this._geometry;
  29692. if (geometry) {
  29693. var geometryId = geometry.id;
  29694. serializationObject.geometryId = geometryId;
  29695. // SubMeshes
  29696. serializationObject.subMeshes = [];
  29697. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29698. var subMesh = this.subMeshes[subIndex];
  29699. serializationObject.subMeshes.push({
  29700. materialIndex: subMesh.materialIndex,
  29701. verticesStart: subMesh.verticesStart,
  29702. verticesCount: subMesh.verticesCount,
  29703. indexStart: subMesh.indexStart,
  29704. indexCount: subMesh.indexCount
  29705. });
  29706. }
  29707. }
  29708. // Material
  29709. if (this.material) {
  29710. serializationObject.materialId = this.material.id;
  29711. }
  29712. else {
  29713. this.material = null;
  29714. }
  29715. // Morph targets
  29716. if (this.morphTargetManager) {
  29717. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29718. }
  29719. // Skeleton
  29720. if (this.skeleton) {
  29721. serializationObject.skeletonId = this.skeleton.id;
  29722. }
  29723. // Physics
  29724. //TODO implement correct serialization for physics impostors.
  29725. var impostor = this.getPhysicsImpostor();
  29726. if (impostor) {
  29727. serializationObject.physicsMass = impostor.getParam("mass");
  29728. serializationObject.physicsFriction = impostor.getParam("friction");
  29729. serializationObject.physicsRestitution = impostor.getParam("mass");
  29730. serializationObject.physicsImpostor = impostor.type;
  29731. }
  29732. // Metadata
  29733. if (this.metadata) {
  29734. serializationObject.metadata = this.metadata;
  29735. }
  29736. // Instances
  29737. serializationObject.instances = [];
  29738. for (var index = 0; index < this.instances.length; index++) {
  29739. var instance = this.instances[index];
  29740. var serializationInstance = {
  29741. name: instance.name,
  29742. id: instance.id,
  29743. position: instance.position.asArray(),
  29744. scaling: instance.scaling.asArray()
  29745. };
  29746. if (instance.rotationQuaternion) {
  29747. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29748. }
  29749. else if (instance.rotation) {
  29750. serializationInstance.rotation = instance.rotation.asArray();
  29751. }
  29752. serializationObject.instances.push(serializationInstance);
  29753. // Animations
  29754. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29755. serializationInstance.ranges = instance.serializeAnimationRanges();
  29756. }
  29757. //
  29758. // Animations
  29759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29760. serializationObject.ranges = this.serializeAnimationRanges();
  29761. // Layer mask
  29762. serializationObject.layerMask = this.layerMask;
  29763. // Alpha
  29764. serializationObject.alphaIndex = this.alphaIndex;
  29765. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29766. // Overlay
  29767. serializationObject.overlayAlpha = this.overlayAlpha;
  29768. serializationObject.overlayColor = this.overlayColor.asArray();
  29769. serializationObject.renderOverlay = this.renderOverlay;
  29770. // Fog
  29771. serializationObject.applyFog = this.applyFog;
  29772. // Action Manager
  29773. if (this.actionManager) {
  29774. serializationObject.actions = this.actionManager.serialize(this.name);
  29775. }
  29776. };
  29777. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29778. if (!this.geometry) {
  29779. return;
  29780. }
  29781. this._markSubMeshesAsAttributesDirty();
  29782. var morphTargetManager = this._morphTargetManager;
  29783. if (morphTargetManager && morphTargetManager.vertexCount) {
  29784. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29785. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29786. this.morphTargetManager = null;
  29787. return;
  29788. }
  29789. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29790. var morphTarget = morphTargetManager.getActiveTarget(index);
  29791. var positions = morphTarget.getPositions();
  29792. if (!positions) {
  29793. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29794. return;
  29795. }
  29796. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29797. var normals = morphTarget.getNormals();
  29798. if (normals) {
  29799. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29800. }
  29801. var tangents = morphTarget.getTangents();
  29802. if (tangents) {
  29803. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29804. }
  29805. }
  29806. }
  29807. else {
  29808. var index = 0;
  29809. // Positions
  29810. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29811. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29812. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29813. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29814. }
  29815. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29816. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29817. }
  29818. index++;
  29819. }
  29820. }
  29821. };
  29822. // Statics
  29823. /**
  29824. * Returns a new Mesh object parsed from the source provided.
  29825. * The parameter `parsedMesh` is the source.
  29826. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29827. */
  29828. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29829. var mesh;
  29830. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29831. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29832. }
  29833. else {
  29834. mesh = new Mesh(parsedMesh.name, scene);
  29835. }
  29836. mesh.id = parsedMesh.id;
  29837. if (BABYLON.Tags) {
  29838. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29839. }
  29840. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29841. if (parsedMesh.metadata !== undefined) {
  29842. mesh.metadata = parsedMesh.metadata;
  29843. }
  29844. if (parsedMesh.rotationQuaternion) {
  29845. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29846. }
  29847. else if (parsedMesh.rotation) {
  29848. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29849. }
  29850. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29851. if (parsedMesh.localMatrix) {
  29852. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29853. }
  29854. else if (parsedMesh.pivotMatrix) {
  29855. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29856. }
  29857. mesh.setEnabled(parsedMesh.isEnabled);
  29858. mesh.isVisible = parsedMesh.isVisible;
  29859. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29860. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29861. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29862. if (parsedMesh.applyFog !== undefined) {
  29863. mesh.applyFog = parsedMesh.applyFog;
  29864. }
  29865. if (parsedMesh.pickable !== undefined) {
  29866. mesh.isPickable = parsedMesh.pickable;
  29867. }
  29868. if (parsedMesh.alphaIndex !== undefined) {
  29869. mesh.alphaIndex = parsedMesh.alphaIndex;
  29870. }
  29871. mesh.receiveShadows = parsedMesh.receiveShadows;
  29872. mesh.billboardMode = parsedMesh.billboardMode;
  29873. if (parsedMesh.visibility !== undefined) {
  29874. mesh.visibility = parsedMesh.visibility;
  29875. }
  29876. mesh.checkCollisions = parsedMesh.checkCollisions;
  29877. if (parsedMesh.isBlocker !== undefined) {
  29878. mesh.isBlocker = parsedMesh.isBlocker;
  29879. }
  29880. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29881. // freezeWorldMatrix
  29882. if (parsedMesh.freezeWorldMatrix) {
  29883. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29884. }
  29885. // Parent
  29886. if (parsedMesh.parentId) {
  29887. mesh._waitingParentId = parsedMesh.parentId;
  29888. }
  29889. // Actions
  29890. if (parsedMesh.actions !== undefined) {
  29891. mesh._waitingActions = parsedMesh.actions;
  29892. }
  29893. // Overlay
  29894. if (parsedMesh.overlayAlpha !== undefined) {
  29895. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29896. }
  29897. if (parsedMesh.overlayColor !== undefined) {
  29898. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29899. }
  29900. if (parsedMesh.renderOverlay !== undefined) {
  29901. mesh.renderOverlay = parsedMesh.renderOverlay;
  29902. }
  29903. // Geometry
  29904. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29905. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29906. if (parsedMesh.delayLoadingFile) {
  29907. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29908. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29909. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29910. if (parsedMesh._binaryInfo) {
  29911. mesh._binaryInfo = parsedMesh._binaryInfo;
  29912. }
  29913. mesh._delayInfo = [];
  29914. if (parsedMesh.hasUVs) {
  29915. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29916. }
  29917. if (parsedMesh.hasUVs2) {
  29918. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29919. }
  29920. if (parsedMesh.hasUVs3) {
  29921. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29922. }
  29923. if (parsedMesh.hasUVs4) {
  29924. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29925. }
  29926. if (parsedMesh.hasUVs5) {
  29927. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29928. }
  29929. if (parsedMesh.hasUVs6) {
  29930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29931. }
  29932. if (parsedMesh.hasColors) {
  29933. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29934. }
  29935. if (parsedMesh.hasMatricesIndices) {
  29936. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29937. }
  29938. if (parsedMesh.hasMatricesWeights) {
  29939. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29940. }
  29941. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29942. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29943. mesh._checkDelayState();
  29944. }
  29945. }
  29946. else {
  29947. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29948. }
  29949. // Material
  29950. if (parsedMesh.materialId) {
  29951. mesh.setMaterialByID(parsedMesh.materialId);
  29952. }
  29953. else {
  29954. mesh.material = null;
  29955. }
  29956. // Morph targets
  29957. if (parsedMesh.morphTargetManagerId > -1) {
  29958. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29959. }
  29960. // Skeleton
  29961. if (parsedMesh.skeletonId > -1) {
  29962. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29963. if (parsedMesh.numBoneInfluencers) {
  29964. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29965. }
  29966. }
  29967. // Animations
  29968. if (parsedMesh.animations) {
  29969. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29970. var parsedAnimation = parsedMesh.animations[animationIndex];
  29971. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29972. }
  29973. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29974. }
  29975. if (parsedMesh.autoAnimate) {
  29976. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29977. }
  29978. // Layer Mask
  29979. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29980. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29981. }
  29982. else {
  29983. mesh.layerMask = 0x0FFFFFFF;
  29984. }
  29985. // Physics
  29986. if (parsedMesh.physicsImpostor) {
  29987. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29988. mass: parsedMesh.physicsMass,
  29989. friction: parsedMesh.physicsFriction,
  29990. restitution: parsedMesh.physicsRestitution
  29991. }, scene);
  29992. }
  29993. // Instances
  29994. if (parsedMesh.instances) {
  29995. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29996. var parsedInstance = parsedMesh.instances[index];
  29997. var instance = mesh.createInstance(parsedInstance.name);
  29998. if (parsedInstance.id) {
  29999. instance.id = parsedInstance.id;
  30000. }
  30001. if (BABYLON.Tags) {
  30002. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  30003. }
  30004. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  30005. if (parsedInstance.parentId) {
  30006. instance._waitingParentId = parsedInstance.parentId;
  30007. }
  30008. if (parsedInstance.rotationQuaternion) {
  30009. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  30010. }
  30011. else if (parsedInstance.rotation) {
  30012. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  30013. }
  30014. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  30015. instance.checkCollisions = mesh.checkCollisions;
  30016. if (parsedMesh.animations) {
  30017. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30018. parsedAnimation = parsedMesh.animations[animationIndex];
  30019. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30020. }
  30021. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30022. }
  30023. }
  30024. }
  30025. return mesh;
  30026. };
  30027. /**
  30028. * Creates a ribbon mesh.
  30029. * Please consider using the same method from the MeshBuilder class instead.
  30030. * 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.
  30031. *
  30032. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30033. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30034. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30035. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30036. * 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.
  30037. * 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.
  30038. * 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
  30039. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30040. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30041. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30042. */
  30043. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30044. if (closeArray === void 0) { closeArray = false; }
  30045. if (updatable === void 0) { updatable = false; }
  30046. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30047. pathArray: pathArray,
  30048. closeArray: closeArray,
  30049. closePath: closePath,
  30050. offset: offset,
  30051. updatable: updatable,
  30052. sideOrientation: sideOrientation,
  30053. instance: instance
  30054. }, scene);
  30055. };
  30056. /**
  30057. * Creates a plane polygonal mesh. By default, this is a disc.
  30058. * Please consider using the same method from the MeshBuilder class instead.
  30059. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30060. * 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.
  30061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30064. */
  30065. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30066. if (scene === void 0) { scene = null; }
  30067. var options = {
  30068. radius: radius,
  30069. tessellation: tessellation,
  30070. sideOrientation: sideOrientation,
  30071. updatable: updatable
  30072. };
  30073. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30074. };
  30075. /**
  30076. * Creates a box mesh.
  30077. * Please consider using the same method from the MeshBuilder class instead.
  30078. * The parameter `size` sets the size (float) of each box side (default 1).
  30079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30082. */
  30083. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30084. if (scene === void 0) { scene = null; }
  30085. var options = {
  30086. size: size,
  30087. sideOrientation: sideOrientation,
  30088. updatable: updatable
  30089. };
  30090. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30091. };
  30092. /**
  30093. * Creates a sphere mesh.
  30094. * Please consider using the same method from the MeshBuilder class instead.
  30095. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30096. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30100. */
  30101. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30102. var options = {
  30103. segments: segments,
  30104. diameterX: diameter,
  30105. diameterY: diameter,
  30106. diameterZ: diameter,
  30107. sideOrientation: sideOrientation,
  30108. updatable: updatable
  30109. };
  30110. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30111. };
  30112. /**
  30113. * Creates a cylinder or a cone mesh.
  30114. * Please consider using the same method from the MeshBuilder class instead.
  30115. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30116. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30117. * 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.
  30118. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30119. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30123. */
  30124. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30125. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30126. if (scene !== undefined) {
  30127. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30128. updatable = scene;
  30129. }
  30130. scene = subdivisions;
  30131. subdivisions = 1;
  30132. }
  30133. var options = {
  30134. height: height,
  30135. diameterTop: diameterTop,
  30136. diameterBottom: diameterBottom,
  30137. tessellation: tessellation,
  30138. subdivisions: subdivisions,
  30139. sideOrientation: sideOrientation,
  30140. updatable: updatable
  30141. };
  30142. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30143. };
  30144. // Torus (Code from SharpDX.org)
  30145. /**
  30146. * Creates a torus mesh.
  30147. * Please consider using the same method from the MeshBuilder class instead.
  30148. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30149. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30150. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30154. */
  30155. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30156. var options = {
  30157. diameter: diameter,
  30158. thickness: thickness,
  30159. tessellation: tessellation,
  30160. sideOrientation: sideOrientation,
  30161. updatable: updatable
  30162. };
  30163. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30164. };
  30165. /**
  30166. * Creates a torus knot mesh.
  30167. * Please consider using the same method from the MeshBuilder class instead.
  30168. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30169. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30170. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30171. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30175. */
  30176. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30177. var options = {
  30178. radius: radius,
  30179. tube: tube,
  30180. radialSegments: radialSegments,
  30181. tubularSegments: tubularSegments,
  30182. p: p,
  30183. q: q,
  30184. sideOrientation: sideOrientation,
  30185. updatable: updatable
  30186. };
  30187. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30188. };
  30189. /**
  30190. * Creates a line mesh.
  30191. * Please consider using the same method from the MeshBuilder class instead.
  30192. * 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.
  30193. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30194. * The parameter `points` is an array successive Vector3.
  30195. * 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
  30196. * When updating an instance, remember that only point positions can change, not the number of points.
  30197. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30198. */
  30199. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30200. if (scene === void 0) { scene = null; }
  30201. if (updatable === void 0) { updatable = false; }
  30202. if (instance === void 0) { instance = null; }
  30203. var options = {
  30204. points: points,
  30205. updatable: updatable,
  30206. instance: instance
  30207. };
  30208. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30209. };
  30210. /**
  30211. * Creates a dashed line mesh.
  30212. * Please consider using the same method from the MeshBuilder class instead.
  30213. * 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.
  30214. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30215. * The parameter `points` is an array successive Vector3.
  30216. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30217. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30218. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30219. * 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
  30220. * When updating an instance, remember that only point positions can change, not the number of points.
  30221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30222. */
  30223. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30224. if (scene === void 0) { scene = null; }
  30225. var options = {
  30226. points: points,
  30227. dashSize: dashSize,
  30228. gapSize: gapSize,
  30229. dashNb: dashNb,
  30230. updatable: updatable,
  30231. instance: instance
  30232. };
  30233. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30234. };
  30235. /**
  30236. * Creates a polygon mesh.
  30237. * Please consider using the same method from the MeshBuilder class instead.
  30238. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30239. * 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.
  30240. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30242. * Remember you can only change the shape positions, not their number when updating a polygon.
  30243. */
  30244. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30245. var options = {
  30246. shape: shape,
  30247. holes: holes,
  30248. updatable: updatable,
  30249. sideOrientation: sideOrientation
  30250. };
  30251. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30252. };
  30253. /**
  30254. * Creates an extruded polygon mesh, with depth in the Y direction.
  30255. * Please consider using the same method from the MeshBuilder class instead.
  30256. */
  30257. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30258. var options = {
  30259. shape: shape,
  30260. holes: holes,
  30261. depth: depth,
  30262. updatable: updatable,
  30263. sideOrientation: sideOrientation
  30264. };
  30265. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30266. };
  30267. /**
  30268. * Creates an extruded shape mesh.
  30269. * 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.
  30270. * Please consider using the same method from the MeshBuilder class instead.
  30271. *
  30272. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30273. * 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
  30274. * extruded along the Z axis.
  30275. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30276. * 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.
  30277. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30278. * 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
  30279. * 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
  30280. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30281. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30282. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30283. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30284. */
  30285. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30286. if (scene === void 0) { scene = null; }
  30287. var options = {
  30288. shape: shape,
  30289. path: path,
  30290. scale: scale,
  30291. rotation: rotation,
  30292. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30293. sideOrientation: sideOrientation,
  30294. instance: instance,
  30295. updatable: updatable
  30296. };
  30297. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30298. };
  30299. /**
  30300. * Creates an custom extruded shape mesh.
  30301. * 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.
  30302. * Please consider using the same method from the MeshBuilder class instead.
  30303. *
  30304. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30305. * 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
  30306. * extruded along the Z axis.
  30307. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30308. * 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
  30309. * and the distance of this point from the begining of the path :
  30310. * ```javascript
  30311. * var rotationFunction = function(i, distance) {
  30312. * // do things
  30313. * return rotationValue; }
  30314. * ```
  30315. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30316. * 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
  30317. * and the distance of this point from the begining of the path :
  30318. * ```javascript
  30319. * var scaleFunction = function(i, distance) {
  30320. * // do things
  30321. * return scaleValue;}
  30322. * ```
  30323. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30324. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30325. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30326. * 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
  30327. * 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
  30328. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30330. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30332. */
  30333. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30334. var options = {
  30335. shape: shape,
  30336. path: path,
  30337. scaleFunction: scaleFunction,
  30338. rotationFunction: rotationFunction,
  30339. ribbonCloseArray: ribbonCloseArray,
  30340. ribbonClosePath: ribbonClosePath,
  30341. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30342. sideOrientation: sideOrientation,
  30343. instance: instance,
  30344. updatable: updatable
  30345. };
  30346. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30347. };
  30348. /**
  30349. * Creates lathe mesh.
  30350. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30351. * Please consider using the same method from the MeshBuilder class instead.
  30352. * 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
  30353. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30354. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30355. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30356. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30359. */
  30360. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30361. var options = {
  30362. shape: shape,
  30363. radius: radius,
  30364. tessellation: tessellation,
  30365. sideOrientation: sideOrientation,
  30366. updatable: updatable
  30367. };
  30368. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30369. };
  30370. /**
  30371. * Creates a plane mesh.
  30372. * Please consider using the same method from the MeshBuilder class instead.
  30373. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30374. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30375. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30377. */
  30378. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30379. var options = {
  30380. size: size,
  30381. width: size,
  30382. height: size,
  30383. sideOrientation: sideOrientation,
  30384. updatable: updatable
  30385. };
  30386. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30387. };
  30388. /**
  30389. * Creates a ground mesh.
  30390. * Please consider using the same method from the MeshBuilder class instead.
  30391. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30392. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30394. */
  30395. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30396. var options = {
  30397. width: width,
  30398. height: height,
  30399. subdivisions: subdivisions,
  30400. updatable: updatable
  30401. };
  30402. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30403. };
  30404. /**
  30405. * Creates a tiled ground mesh.
  30406. * Please consider using the same method from the MeshBuilder class instead.
  30407. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30408. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30409. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30410. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30411. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30412. * numbers of subdivisions on the ground width and height of each tile.
  30413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30414. */
  30415. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30416. var options = {
  30417. xmin: xmin,
  30418. zmin: zmin,
  30419. xmax: xmax,
  30420. zmax: zmax,
  30421. subdivisions: subdivisions,
  30422. precision: precision,
  30423. updatable: updatable
  30424. };
  30425. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30426. };
  30427. /**
  30428. * Creates a ground mesh from a height map.
  30429. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30430. * Please consider using the same method from the MeshBuilder class instead.
  30431. * The parameter `url` sets the URL of the height map image resource.
  30432. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30433. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30434. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30435. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30436. * 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).
  30437. * This function is passed the newly built mesh :
  30438. * ```javascript
  30439. * function(mesh) { // do things
  30440. * return; }
  30441. * ```
  30442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30443. */
  30444. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30445. var options = {
  30446. width: width,
  30447. height: height,
  30448. subdivisions: subdivisions,
  30449. minHeight: minHeight,
  30450. maxHeight: maxHeight,
  30451. updatable: updatable,
  30452. onReady: onReady
  30453. };
  30454. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30455. };
  30456. /**
  30457. * Creates a tube mesh.
  30458. * 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.
  30459. * Please consider using the same method from the MeshBuilder class instead.
  30460. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30461. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30462. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30463. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30464. * 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.
  30465. * It must return a radius value (positive float) :
  30466. * ```javascript
  30467. * var radiusFunction = function(i, distance) {
  30468. * // do things
  30469. * return radius; }
  30470. * ```
  30471. * 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
  30472. * 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
  30473. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30474. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30475. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30476. */
  30477. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30478. var options = {
  30479. path: path,
  30480. radius: radius,
  30481. tessellation: tessellation,
  30482. radiusFunction: radiusFunction,
  30483. arc: 1,
  30484. cap: cap,
  30485. updatable: updatable,
  30486. sideOrientation: sideOrientation,
  30487. instance: instance
  30488. };
  30489. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30490. };
  30491. /**
  30492. * Creates a polyhedron mesh.
  30493. * Please consider using the same method from the MeshBuilder class instead.
  30494. * 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
  30495. * to choose the wanted type.
  30496. * The parameter `size` (positive float, default 1) sets the polygon size.
  30497. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30498. * 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`.
  30499. * 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
  30500. * 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)`).
  30501. * 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
  30502. * 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.
  30503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30506. */
  30507. Mesh.CreatePolyhedron = function (name, options, scene) {
  30508. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30509. };
  30510. /**
  30511. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30512. * Please consider using the same method from the MeshBuilder class instead.
  30513. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30514. * 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`).
  30515. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30516. * 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.
  30517. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30518. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30519. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30520. */
  30521. Mesh.CreateIcoSphere = function (name, options, scene) {
  30522. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30523. };
  30524. /**
  30525. * Creates a decal mesh.
  30526. * Please consider using the same method from the MeshBuilder class instead.
  30527. * 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.
  30528. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30529. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30530. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30531. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30532. */
  30533. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30534. var options = {
  30535. position: position,
  30536. normal: normal,
  30537. size: size,
  30538. angle: angle
  30539. };
  30540. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30541. };
  30542. // Skeletons
  30543. /**
  30544. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30545. */
  30546. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30547. if (!this._sourcePositions) {
  30548. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30549. if (!source) {
  30550. return this._sourcePositions;
  30551. }
  30552. this._sourcePositions = new Float32Array(source);
  30553. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30554. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30555. }
  30556. }
  30557. return this._sourcePositions;
  30558. };
  30559. /**
  30560. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30561. */
  30562. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30563. if (!this._sourceNormals) {
  30564. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30565. if (!source) {
  30566. return this._sourceNormals;
  30567. }
  30568. this._sourceNormals = new Float32Array(source);
  30569. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30570. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30571. }
  30572. }
  30573. return this._sourceNormals;
  30574. };
  30575. /**
  30576. * Updates the vertex buffer by applying transformation from the bones.
  30577. * Returns the Mesh.
  30578. *
  30579. * @param {skeleton} skeleton to apply
  30580. */
  30581. Mesh.prototype.applySkeleton = function (skeleton) {
  30582. if (!this.geometry) {
  30583. return this;
  30584. }
  30585. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30586. return this;
  30587. }
  30588. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30589. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30590. return this;
  30591. }
  30592. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30593. return this;
  30594. }
  30595. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30596. return this;
  30597. }
  30598. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30599. return this;
  30600. }
  30601. if (!this._sourcePositions) {
  30602. var submeshes = this.subMeshes.slice();
  30603. this.setPositionsForCPUSkinning();
  30604. this.subMeshes = submeshes;
  30605. }
  30606. if (!this._sourceNormals) {
  30607. this.setNormalsForCPUSkinning();
  30608. }
  30609. // positionsData checks for not being Float32Array will only pass at most once
  30610. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30611. if (!positionsData) {
  30612. return this;
  30613. }
  30614. if (!(positionsData instanceof Float32Array)) {
  30615. positionsData = new Float32Array(positionsData);
  30616. }
  30617. // normalsData checks for not being Float32Array will only pass at most once
  30618. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30619. if (!normalsData) {
  30620. return this;
  30621. }
  30622. if (!(normalsData instanceof Float32Array)) {
  30623. normalsData = new Float32Array(normalsData);
  30624. }
  30625. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30626. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30627. if (!matricesWeightsData || !matricesIndicesData) {
  30628. return this;
  30629. }
  30630. var needExtras = this.numBoneInfluencers > 4;
  30631. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30632. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30633. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30634. var tempVector3 = BABYLON.Vector3.Zero();
  30635. var finalMatrix = new BABYLON.Matrix();
  30636. var tempMatrix = new BABYLON.Matrix();
  30637. var matWeightIdx = 0;
  30638. var inf;
  30639. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30640. var weight;
  30641. for (inf = 0; inf < 4; inf++) {
  30642. weight = matricesWeightsData[matWeightIdx + inf];
  30643. if (weight > 0) {
  30644. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30645. finalMatrix.addToSelf(tempMatrix);
  30646. }
  30647. else
  30648. break;
  30649. }
  30650. if (needExtras) {
  30651. for (inf = 0; inf < 4; inf++) {
  30652. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30653. if (weight > 0) {
  30654. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30655. finalMatrix.addToSelf(tempMatrix);
  30656. }
  30657. else
  30658. break;
  30659. }
  30660. }
  30661. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30662. tempVector3.toArray(positionsData, index);
  30663. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30664. tempVector3.toArray(normalsData, index);
  30665. finalMatrix.reset();
  30666. }
  30667. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30668. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30669. return this;
  30670. };
  30671. // Tools
  30672. /**
  30673. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30674. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30675. */
  30676. Mesh.MinMax = function (meshes) {
  30677. var minVector = null;
  30678. var maxVector = null;
  30679. meshes.forEach(function (mesh, index, array) {
  30680. var boundingInfo = mesh.getBoundingInfo();
  30681. var boundingBox = boundingInfo.boundingBox;
  30682. if (!minVector || !maxVector) {
  30683. minVector = boundingBox.minimumWorld;
  30684. maxVector = boundingBox.maximumWorld;
  30685. }
  30686. else {
  30687. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30688. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30689. }
  30690. });
  30691. if (!minVector || !maxVector) {
  30692. return {
  30693. min: BABYLON.Vector3.Zero(),
  30694. max: BABYLON.Vector3.Zero()
  30695. };
  30696. }
  30697. return {
  30698. min: minVector,
  30699. max: maxVector
  30700. };
  30701. };
  30702. /**
  30703. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30704. */
  30705. Mesh.Center = function (meshesOrMinMaxVector) {
  30706. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30707. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30708. };
  30709. /**
  30710. * Merge the array of meshes into a single mesh for performance reasons.
  30711. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30712. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30713. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30714. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30715. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30716. */
  30717. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30718. if (disposeSource === void 0) { disposeSource = true; }
  30719. var index;
  30720. if (!allow32BitsIndices) {
  30721. var totalVertices = 0;
  30722. // Counting vertices
  30723. for (index = 0; index < meshes.length; index++) {
  30724. if (meshes[index]) {
  30725. totalVertices += meshes[index].getTotalVertices();
  30726. if (totalVertices > 65536) {
  30727. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30728. return null;
  30729. }
  30730. }
  30731. }
  30732. }
  30733. // Merge
  30734. var vertexData = null;
  30735. var otherVertexData;
  30736. var indiceArray = new Array();
  30737. var source = null;
  30738. for (index = 0; index < meshes.length; index++) {
  30739. if (meshes[index]) {
  30740. meshes[index].computeWorldMatrix(true);
  30741. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30742. otherVertexData.transform(meshes[index].getWorldMatrix());
  30743. if (vertexData) {
  30744. vertexData.merge(otherVertexData);
  30745. }
  30746. else {
  30747. vertexData = otherVertexData;
  30748. source = meshes[index];
  30749. }
  30750. if (subdivideWithSubMeshes) {
  30751. indiceArray.push(meshes[index].getTotalIndices());
  30752. }
  30753. }
  30754. }
  30755. source = source;
  30756. if (!meshSubclass) {
  30757. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30758. }
  30759. vertexData.applyToMesh(meshSubclass);
  30760. // Setting properties
  30761. meshSubclass.material = source.material;
  30762. meshSubclass.checkCollisions = source.checkCollisions;
  30763. // Cleaning
  30764. if (disposeSource) {
  30765. for (index = 0; index < meshes.length; index++) {
  30766. if (meshes[index]) {
  30767. meshes[index].dispose();
  30768. }
  30769. }
  30770. }
  30771. // Subdivide
  30772. if (subdivideWithSubMeshes) {
  30773. //-- Suppresions du submesh global
  30774. meshSubclass.releaseSubMeshes();
  30775. index = 0;
  30776. var offset = 0;
  30777. //-- aplique la subdivision en fonction du tableau d'indices
  30778. while (index < indiceArray.length) {
  30779. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30780. offset += indiceArray[index];
  30781. index++;
  30782. }
  30783. }
  30784. return meshSubclass;
  30785. };
  30786. // Consts
  30787. Mesh._FRONTSIDE = 0;
  30788. Mesh._BACKSIDE = 1;
  30789. Mesh._DOUBLESIDE = 2;
  30790. Mesh._DEFAULTSIDE = 0;
  30791. Mesh._NO_CAP = 0;
  30792. Mesh._CAP_START = 1;
  30793. Mesh._CAP_END = 2;
  30794. Mesh._CAP_ALL = 3;
  30795. return Mesh;
  30796. }(BABYLON.AbstractMesh));
  30797. BABYLON.Mesh = Mesh;
  30798. })(BABYLON || (BABYLON = {}));
  30799. //# sourceMappingURL=babylon.mesh.js.map
  30800. "use strict";
  30801. var BABYLON;
  30802. (function (BABYLON) {
  30803. var BaseSubMesh = /** @class */ (function () {
  30804. function BaseSubMesh() {
  30805. }
  30806. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30807. get: function () {
  30808. return this._materialEffect;
  30809. },
  30810. enumerable: true,
  30811. configurable: true
  30812. });
  30813. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30814. if (defines === void 0) { defines = null; }
  30815. if (this._materialEffect === effect) {
  30816. if (!effect) {
  30817. this._materialDefines = null;
  30818. }
  30819. return;
  30820. }
  30821. this._materialDefines = defines;
  30822. this._materialEffect = effect;
  30823. };
  30824. return BaseSubMesh;
  30825. }());
  30826. BABYLON.BaseSubMesh = BaseSubMesh;
  30827. var SubMesh = /** @class */ (function (_super) {
  30828. __extends(SubMesh, _super);
  30829. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30830. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30831. var _this = _super.call(this) || this;
  30832. _this.materialIndex = materialIndex;
  30833. _this.verticesStart = verticesStart;
  30834. _this.verticesCount = verticesCount;
  30835. _this.indexStart = indexStart;
  30836. _this.indexCount = indexCount;
  30837. _this._renderId = 0;
  30838. _this._mesh = mesh;
  30839. _this._renderingMesh = renderingMesh || mesh;
  30840. mesh.subMeshes.push(_this);
  30841. _this._trianglePlanes = [];
  30842. _this._id = mesh.subMeshes.length - 1;
  30843. if (createBoundingBox) {
  30844. _this.refreshBoundingInfo();
  30845. mesh.computeWorldMatrix(true);
  30846. }
  30847. return _this;
  30848. }
  30849. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30850. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30851. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30852. };
  30853. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30854. get: function () {
  30855. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30856. },
  30857. enumerable: true,
  30858. configurable: true
  30859. });
  30860. /**
  30861. * Returns the submesh BoudingInfo object.
  30862. */
  30863. SubMesh.prototype.getBoundingInfo = function () {
  30864. if (this.IsGlobal) {
  30865. return this._mesh.getBoundingInfo();
  30866. }
  30867. return this._boundingInfo;
  30868. };
  30869. /**
  30870. * Sets the submesh BoundingInfo.
  30871. * Return the SubMesh.
  30872. */
  30873. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30874. this._boundingInfo = boundingInfo;
  30875. return this;
  30876. };
  30877. /**
  30878. * Returns the mesh of the current submesh.
  30879. */
  30880. SubMesh.prototype.getMesh = function () {
  30881. return this._mesh;
  30882. };
  30883. /**
  30884. * Returns the rendering mesh of the submesh.
  30885. */
  30886. SubMesh.prototype.getRenderingMesh = function () {
  30887. return this._renderingMesh;
  30888. };
  30889. /**
  30890. * Returns the submesh material.
  30891. */
  30892. SubMesh.prototype.getMaterial = function () {
  30893. var rootMaterial = this._renderingMesh.material;
  30894. if (rootMaterial === null || rootMaterial === undefined) {
  30895. return this._mesh.getScene().defaultMaterial;
  30896. }
  30897. else if (rootMaterial.getSubMaterial) {
  30898. var multiMaterial = rootMaterial;
  30899. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30900. if (this._currentMaterial !== effectiveMaterial) {
  30901. this._currentMaterial = effectiveMaterial;
  30902. this._materialDefines = null;
  30903. }
  30904. return effectiveMaterial;
  30905. }
  30906. return rootMaterial;
  30907. };
  30908. // Methods
  30909. /**
  30910. * Sets a new updated BoundingInfo object to the submesh.
  30911. * Returns the SubMesh.
  30912. */
  30913. SubMesh.prototype.refreshBoundingInfo = function () {
  30914. this._lastColliderWorldVertices = null;
  30915. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30916. return this;
  30917. }
  30918. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30919. if (!data) {
  30920. this._boundingInfo = this._mesh.getBoundingInfo();
  30921. return this;
  30922. }
  30923. var indices = this._renderingMesh.getIndices();
  30924. var extend;
  30925. //is this the only submesh?
  30926. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30927. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30928. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30929. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30930. }
  30931. else {
  30932. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30933. }
  30934. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30935. return this;
  30936. };
  30937. SubMesh.prototype._checkCollision = function (collider) {
  30938. var boundingInfo = this.getBoundingInfo();
  30939. return boundingInfo._checkCollision(collider);
  30940. };
  30941. /**
  30942. * Updates the submesh BoundingInfo.
  30943. * Returns the Submesh.
  30944. */
  30945. SubMesh.prototype.updateBoundingInfo = function (world) {
  30946. var boundingInfo = this.getBoundingInfo();
  30947. if (!boundingInfo) {
  30948. this.refreshBoundingInfo();
  30949. boundingInfo = this.getBoundingInfo();
  30950. }
  30951. boundingInfo.update(world);
  30952. return this;
  30953. };
  30954. /**
  30955. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30956. * Boolean returned.
  30957. */
  30958. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30959. var boundingInfo = this.getBoundingInfo();
  30960. if (!boundingInfo) {
  30961. return false;
  30962. }
  30963. return boundingInfo.isInFrustum(frustumPlanes);
  30964. };
  30965. /**
  30966. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30967. * Boolean returned.
  30968. */
  30969. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30970. var boundingInfo = this.getBoundingInfo();
  30971. if (!boundingInfo) {
  30972. return false;
  30973. }
  30974. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30975. };
  30976. /**
  30977. * Renders the submesh.
  30978. * Returns it.
  30979. */
  30980. SubMesh.prototype.render = function (enableAlphaMode) {
  30981. this._renderingMesh.render(this, enableAlphaMode);
  30982. return this;
  30983. };
  30984. /**
  30985. * Returns a new Index Buffer.
  30986. * Type returned : WebGLBuffer.
  30987. */
  30988. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30989. if (!this._linesIndexBuffer) {
  30990. var linesIndices = [];
  30991. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30992. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30993. }
  30994. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30995. this.linesIndexCount = linesIndices.length;
  30996. }
  30997. return this._linesIndexBuffer;
  30998. };
  30999. /**
  31000. * True is the passed Ray intersects the submesh bounding box.
  31001. * Boolean returned.
  31002. */
  31003. SubMesh.prototype.canIntersects = function (ray) {
  31004. var boundingInfo = this.getBoundingInfo();
  31005. if (!boundingInfo) {
  31006. return false;
  31007. }
  31008. return ray.intersectsBox(boundingInfo.boundingBox);
  31009. };
  31010. /**
  31011. * Returns an object IntersectionInfo.
  31012. */
  31013. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  31014. var intersectInfo = null;
  31015. var material = this.getMaterial();
  31016. if (!material) {
  31017. return null;
  31018. }
  31019. switch (material.fillMode) {
  31020. case BABYLON.Material.PointListDrawMode:
  31021. case BABYLON.Material.LineListDrawMode:
  31022. case BABYLON.Material.LineLoopDrawMode:
  31023. case BABYLON.Material.LineStripDrawMode:
  31024. case BABYLON.Material.TriangleFanDrawMode:
  31025. case BABYLON.Material.TriangleStripDrawMode:
  31026. return null;
  31027. }
  31028. // LineMesh first as it's also a Mesh...
  31029. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31030. var lineMesh = this._mesh;
  31031. // Line test
  31032. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31033. var p0 = positions[indices[index]];
  31034. var p1 = positions[indices[index + 1]];
  31035. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31036. if (length < 0) {
  31037. continue;
  31038. }
  31039. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31040. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31041. if (fastCheck) {
  31042. break;
  31043. }
  31044. }
  31045. }
  31046. }
  31047. else {
  31048. // Triangles test
  31049. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31050. var p0 = positions[indices[index]];
  31051. var p1 = positions[indices[index + 1]];
  31052. var p2 = positions[indices[index + 2]];
  31053. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31054. if (currentIntersectInfo) {
  31055. if (currentIntersectInfo.distance < 0) {
  31056. continue;
  31057. }
  31058. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31059. intersectInfo = currentIntersectInfo;
  31060. intersectInfo.faceId = index / 3;
  31061. if (fastCheck) {
  31062. break;
  31063. }
  31064. }
  31065. }
  31066. }
  31067. }
  31068. return intersectInfo;
  31069. };
  31070. SubMesh.prototype._rebuild = function () {
  31071. if (this._linesIndexBuffer) {
  31072. this._linesIndexBuffer = null;
  31073. }
  31074. };
  31075. // Clone
  31076. /**
  31077. * Creates a new Submesh from the passed Mesh.
  31078. */
  31079. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31080. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31081. if (!this.IsGlobal) {
  31082. var boundingInfo = this.getBoundingInfo();
  31083. if (!boundingInfo) {
  31084. return result;
  31085. }
  31086. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31087. }
  31088. return result;
  31089. };
  31090. // Dispose
  31091. /**
  31092. * Disposes the Submesh.
  31093. * Returns nothing.
  31094. */
  31095. SubMesh.prototype.dispose = function () {
  31096. if (this._linesIndexBuffer) {
  31097. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31098. this._linesIndexBuffer = null;
  31099. }
  31100. // Remove from mesh
  31101. var index = this._mesh.subMeshes.indexOf(this);
  31102. this._mesh.subMeshes.splice(index, 1);
  31103. };
  31104. // Statics
  31105. /**
  31106. * Creates a new Submesh from the passed parameters :
  31107. * - materialIndex (integer) : the index of the main mesh material.
  31108. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31109. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31110. * - mesh (Mesh) : the main mesh to create the submesh from.
  31111. * - renderingMesh (optional Mesh) : rendering mesh.
  31112. */
  31113. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31114. var minVertexIndex = Number.MAX_VALUE;
  31115. var maxVertexIndex = -Number.MAX_VALUE;
  31116. renderingMesh = (renderingMesh || mesh);
  31117. var indices = renderingMesh.getIndices();
  31118. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31119. var vertexIndex = indices[index];
  31120. if (vertexIndex < minVertexIndex)
  31121. minVertexIndex = vertexIndex;
  31122. if (vertexIndex > maxVertexIndex)
  31123. maxVertexIndex = vertexIndex;
  31124. }
  31125. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31126. };
  31127. return SubMesh;
  31128. }(BaseSubMesh));
  31129. BABYLON.SubMesh = SubMesh;
  31130. })(BABYLON || (BABYLON = {}));
  31131. //# sourceMappingURL=babylon.subMesh.js.map
  31132. "use strict";
  31133. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31134. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31135. s = arguments[i];
  31136. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31137. t[p] = s[p];
  31138. }
  31139. return t;
  31140. };
  31141. var BABYLON;
  31142. (function (BABYLON) {
  31143. /**
  31144. * Manages the defines for the Material.
  31145. */
  31146. var MaterialDefines = /** @class */ (function () {
  31147. function MaterialDefines() {
  31148. this._isDirty = true;
  31149. this._areLightsDirty = true;
  31150. this._areAttributesDirty = true;
  31151. this._areTexturesDirty = true;
  31152. this._areFresnelDirty = true;
  31153. this._areMiscDirty = true;
  31154. this._areImageProcessingDirty = true;
  31155. this._normals = false;
  31156. this._uvs = false;
  31157. this._needNormals = false;
  31158. this._needUVs = false;
  31159. }
  31160. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31161. /**
  31162. * Specifies if the material needs to be re-calculated.
  31163. */
  31164. get: function () {
  31165. return this._isDirty;
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. /**
  31171. * Marks the material to indicate that it has been re-calculated.
  31172. */
  31173. MaterialDefines.prototype.markAsProcessed = function () {
  31174. this._isDirty = false;
  31175. this._areAttributesDirty = false;
  31176. this._areTexturesDirty = false;
  31177. this._areFresnelDirty = false;
  31178. this._areLightsDirty = false;
  31179. this._areMiscDirty = false;
  31180. this._areImageProcessingDirty = false;
  31181. };
  31182. /**
  31183. * Marks the material to indicate that it needs to be re-calculated.
  31184. */
  31185. MaterialDefines.prototype.markAsUnprocessed = function () {
  31186. this._isDirty = true;
  31187. };
  31188. /**
  31189. * Marks the material to indicate all of its defines need to be re-calculated.
  31190. */
  31191. MaterialDefines.prototype.markAllAsDirty = function () {
  31192. this._areTexturesDirty = true;
  31193. this._areAttributesDirty = true;
  31194. this._areLightsDirty = true;
  31195. this._areFresnelDirty = true;
  31196. this._areMiscDirty = true;
  31197. this._areImageProcessingDirty = true;
  31198. this._isDirty = true;
  31199. };
  31200. /**
  31201. * Marks the material to indicate that image processing needs to be re-calculated.
  31202. */
  31203. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31204. this._areImageProcessingDirty = true;
  31205. this._isDirty = true;
  31206. };
  31207. /**
  31208. * Marks the material to indicate the lights need to be re-calculated.
  31209. */
  31210. MaterialDefines.prototype.markAsLightDirty = function () {
  31211. this._areLightsDirty = true;
  31212. this._isDirty = true;
  31213. };
  31214. /**
  31215. * Marks the attribute state as changed.
  31216. */
  31217. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31218. this._areAttributesDirty = true;
  31219. this._isDirty = true;
  31220. };
  31221. /**
  31222. * Marks the texture state as changed.
  31223. */
  31224. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31225. this._areTexturesDirty = true;
  31226. this._isDirty = true;
  31227. };
  31228. /**
  31229. * Marks the fresnel state as changed.
  31230. */
  31231. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31232. this._areFresnelDirty = true;
  31233. this._isDirty = true;
  31234. };
  31235. /**
  31236. * Marks the misc state as changed.
  31237. */
  31238. MaterialDefines.prototype.markAsMiscDirty = function () {
  31239. this._areMiscDirty = true;
  31240. this._isDirty = true;
  31241. };
  31242. /**
  31243. * Rebuilds the material defines.
  31244. */
  31245. MaterialDefines.prototype.rebuild = function () {
  31246. if (this._keys) {
  31247. delete this._keys;
  31248. }
  31249. this._keys = [];
  31250. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31251. var key = _a[_i];
  31252. if (key[0] === "_") {
  31253. continue;
  31254. }
  31255. this._keys.push(key);
  31256. }
  31257. };
  31258. /**
  31259. * Specifies if two material defines are equal.
  31260. * @param other - A material define instance to compare to.
  31261. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31262. */
  31263. MaterialDefines.prototype.isEqual = function (other) {
  31264. if (this._keys.length !== other._keys.length) {
  31265. return false;
  31266. }
  31267. for (var index = 0; index < this._keys.length; index++) {
  31268. var prop = this._keys[index];
  31269. if (this[prop] !== other[prop]) {
  31270. return false;
  31271. }
  31272. }
  31273. return true;
  31274. };
  31275. /**
  31276. * Clones this instance's defines to another instance.
  31277. * @param other - material defines to clone values to.
  31278. */
  31279. MaterialDefines.prototype.cloneTo = function (other) {
  31280. if (this._keys.length !== other._keys.length) {
  31281. other._keys = this._keys.slice(0);
  31282. }
  31283. for (var index = 0; index < this._keys.length; index++) {
  31284. var prop = this._keys[index];
  31285. other[prop] = this[prop];
  31286. }
  31287. };
  31288. /**
  31289. * Resets the material define values.
  31290. */
  31291. MaterialDefines.prototype.reset = function () {
  31292. for (var index = 0; index < this._keys.length; index++) {
  31293. var prop = this._keys[index];
  31294. var type = typeof this[prop];
  31295. switch (type) {
  31296. case "number":
  31297. this[prop] = 0;
  31298. break;
  31299. case "string":
  31300. this[prop] = "";
  31301. break;
  31302. default:
  31303. this[prop] = false;
  31304. break;
  31305. }
  31306. }
  31307. };
  31308. /**
  31309. * Converts the material define values to a string.
  31310. * @returns - String of material define information.
  31311. */
  31312. MaterialDefines.prototype.toString = function () {
  31313. var result = "";
  31314. for (var index = 0; index < this._keys.length; index++) {
  31315. var prop = this._keys[index];
  31316. var value = this[prop];
  31317. var type = typeof value;
  31318. switch (type) {
  31319. case "number":
  31320. case "string":
  31321. result += "#define " + prop + " " + value + "\n";
  31322. break;
  31323. default:
  31324. if (value) {
  31325. result += "#define " + prop + "\n";
  31326. }
  31327. break;
  31328. }
  31329. }
  31330. return result;
  31331. };
  31332. return MaterialDefines;
  31333. }());
  31334. BABYLON.MaterialDefines = MaterialDefines;
  31335. /**
  31336. * This offers the main features of a material in BJS.
  31337. */
  31338. var Material = /** @class */ (function () {
  31339. /**
  31340. * Creates a material instance.
  31341. * @param name - The name of the material.
  31342. * @param scene - The BJS scene to reference.
  31343. * @param doNotAdd - Specifies if the material should be added to the scene.
  31344. */
  31345. function Material(name, scene, doNotAdd) {
  31346. /**
  31347. * Specifies if the ready state should be checked on each call.
  31348. */
  31349. this.checkReadyOnEveryCall = false;
  31350. /**
  31351. * Specifies if the ready state should be checked once.
  31352. */
  31353. this.checkReadyOnlyOnce = false;
  31354. /**
  31355. * The state of the material.
  31356. */
  31357. this.state = "";
  31358. /**
  31359. * The alpha value of the material.
  31360. */
  31361. this._alpha = 1.0;
  31362. /**
  31363. * Specifies if back face culling is enabled.
  31364. */
  31365. this._backFaceCulling = true;
  31366. /**
  31367. * Specifies if the material should be serialized.
  31368. */
  31369. this.doNotSerialize = false;
  31370. /**
  31371. * Specifies if the effect should be stored on sub meshes.
  31372. */
  31373. this.storeEffectOnSubMeshes = false;
  31374. /**
  31375. * An event triggered when the material is disposed.
  31376. * @type {BABYLON.Observable}
  31377. */
  31378. this.onDisposeObservable = new BABYLON.Observable();
  31379. /**
  31380. * An event triggered when the material is bound.
  31381. * @type {BABYLON.Observable}
  31382. */
  31383. this.onBindObservable = new BABYLON.Observable();
  31384. /**
  31385. * An event triggered when the material is unbound.
  31386. * @type {BABYLON.Observable}
  31387. */
  31388. this.onUnBindObservable = new BABYLON.Observable();
  31389. /**
  31390. * Stores the value of the alpha mode.
  31391. */
  31392. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31393. /**
  31394. * Stores the state of the need depth pre-pass value.
  31395. */
  31396. this._needDepthPrePass = false;
  31397. /**
  31398. * Specifies if depth writing should be disabled.
  31399. */
  31400. this.disableDepthWrite = false;
  31401. /**
  31402. * Specifies if depth writing should be forced.
  31403. */
  31404. this.forceDepthWrite = false;
  31405. /**
  31406. * Specifies if there should be a separate pass for culling.
  31407. */
  31408. this.separateCullingPass = false;
  31409. /**
  31410. * Stores the state specifing if fog should be enabled.
  31411. */
  31412. this._fogEnabled = true;
  31413. /**
  31414. * Stores the size of points.
  31415. */
  31416. this.pointSize = 1.0;
  31417. /**
  31418. * Stores the z offset value.
  31419. */
  31420. this.zOffset = 0;
  31421. /**
  31422. * Specifies if the material was previously ready.
  31423. */
  31424. this._wasPreviouslyReady = false;
  31425. /**
  31426. * Stores the fill mode state.
  31427. */
  31428. this._fillMode = Material.TriangleFillMode;
  31429. this.name = name;
  31430. this.id = name || BABYLON.Tools.RandomId();
  31431. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31432. if (this._scene.useRightHandedSystem) {
  31433. this.sideOrientation = Material.ClockWiseSideOrientation;
  31434. }
  31435. else {
  31436. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31437. }
  31438. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31439. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31440. if (!doNotAdd) {
  31441. this._scene.materials.push(this);
  31442. }
  31443. }
  31444. Object.defineProperty(Material, "TriangleFillMode", {
  31445. /**
  31446. * Returns the triangle fill mode.
  31447. */
  31448. get: function () {
  31449. return Material._TriangleFillMode;
  31450. },
  31451. enumerable: true,
  31452. configurable: true
  31453. });
  31454. Object.defineProperty(Material, "WireFrameFillMode", {
  31455. /**
  31456. * Returns the wireframe mode.
  31457. */
  31458. get: function () {
  31459. return Material._WireFrameFillMode;
  31460. },
  31461. enumerable: true,
  31462. configurable: true
  31463. });
  31464. Object.defineProperty(Material, "PointFillMode", {
  31465. /**
  31466. * Returns the point fill mode.
  31467. */
  31468. get: function () {
  31469. return Material._PointFillMode;
  31470. },
  31471. enumerable: true,
  31472. configurable: true
  31473. });
  31474. Object.defineProperty(Material, "PointListDrawMode", {
  31475. /**
  31476. * Returns the point list draw mode.
  31477. */
  31478. get: function () {
  31479. return Material._PointListDrawMode;
  31480. },
  31481. enumerable: true,
  31482. configurable: true
  31483. });
  31484. Object.defineProperty(Material, "LineListDrawMode", {
  31485. /**
  31486. * Returns the line list draw mode.
  31487. */
  31488. get: function () {
  31489. return Material._LineListDrawMode;
  31490. },
  31491. enumerable: true,
  31492. configurable: true
  31493. });
  31494. Object.defineProperty(Material, "LineLoopDrawMode", {
  31495. /**
  31496. * Returns the line loop draw mode.
  31497. */
  31498. get: function () {
  31499. return Material._LineLoopDrawMode;
  31500. },
  31501. enumerable: true,
  31502. configurable: true
  31503. });
  31504. Object.defineProperty(Material, "LineStripDrawMode", {
  31505. /**
  31506. * Returns the line strip draw mode.
  31507. */
  31508. get: function () {
  31509. return Material._LineStripDrawMode;
  31510. },
  31511. enumerable: true,
  31512. configurable: true
  31513. });
  31514. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31515. /**
  31516. * Returns the triangle strip draw mode.
  31517. */
  31518. get: function () {
  31519. return Material._TriangleStripDrawMode;
  31520. },
  31521. enumerable: true,
  31522. configurable: true
  31523. });
  31524. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31525. /**
  31526. * Returns the triangle fan draw mode.
  31527. */
  31528. get: function () {
  31529. return Material._TriangleFanDrawMode;
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31535. /**
  31536. * Returns the clock-wise side orientation.
  31537. */
  31538. get: function () {
  31539. return Material._ClockWiseSideOrientation;
  31540. },
  31541. enumerable: true,
  31542. configurable: true
  31543. });
  31544. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31545. /**
  31546. * Returns the counter clock-wise side orientation.
  31547. */
  31548. get: function () {
  31549. return Material._CounterClockWiseSideOrientation;
  31550. },
  31551. enumerable: true,
  31552. configurable: true
  31553. });
  31554. Object.defineProperty(Material, "TextureDirtyFlag", {
  31555. /**
  31556. * Returns the dirty texture flag value.
  31557. */
  31558. get: function () {
  31559. return Material._TextureDirtyFlag;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. Object.defineProperty(Material, "LightDirtyFlag", {
  31565. /**
  31566. * Returns the dirty light flag value.
  31567. */
  31568. get: function () {
  31569. return Material._LightDirtyFlag;
  31570. },
  31571. enumerable: true,
  31572. configurable: true
  31573. });
  31574. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31575. /**
  31576. * Returns the dirty fresnel flag value.
  31577. */
  31578. get: function () {
  31579. return Material._FresnelDirtyFlag;
  31580. },
  31581. enumerable: true,
  31582. configurable: true
  31583. });
  31584. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31585. /**
  31586. * Returns the dirty attributes flag value.
  31587. */
  31588. get: function () {
  31589. return Material._AttributesDirtyFlag;
  31590. },
  31591. enumerable: true,
  31592. configurable: true
  31593. });
  31594. Object.defineProperty(Material, "MiscDirtyFlag", {
  31595. /**
  31596. * Returns the dirty misc flag value.
  31597. */
  31598. get: function () {
  31599. return Material._MiscDirtyFlag;
  31600. },
  31601. enumerable: true,
  31602. configurable: true
  31603. });
  31604. Object.defineProperty(Material.prototype, "alpha", {
  31605. /**
  31606. * Gets the alpha value of the material.
  31607. */
  31608. get: function () {
  31609. return this._alpha;
  31610. },
  31611. /**
  31612. * Sets the alpha value of the material.
  31613. */
  31614. set: function (value) {
  31615. if (this._alpha === value) {
  31616. return;
  31617. }
  31618. this._alpha = value;
  31619. this.markAsDirty(Material.MiscDirtyFlag);
  31620. },
  31621. enumerable: true,
  31622. configurable: true
  31623. });
  31624. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31625. /**
  31626. * Gets the back-face culling state.
  31627. */
  31628. get: function () {
  31629. return this._backFaceCulling;
  31630. },
  31631. /**
  31632. * Sets the back-face culling state.
  31633. */
  31634. set: function (value) {
  31635. if (this._backFaceCulling === value) {
  31636. return;
  31637. }
  31638. this._backFaceCulling = value;
  31639. this.markAsDirty(Material.TextureDirtyFlag);
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Object.defineProperty(Material.prototype, "onDispose", {
  31645. /**
  31646. * Called during a dispose event.
  31647. */
  31648. set: function (callback) {
  31649. if (this._onDisposeObserver) {
  31650. this.onDisposeObservable.remove(this._onDisposeObserver);
  31651. }
  31652. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31653. },
  31654. enumerable: true,
  31655. configurable: true
  31656. });
  31657. Object.defineProperty(Material.prototype, "onBind", {
  31658. /**
  31659. * Called during a bind event.
  31660. */
  31661. set: function (callback) {
  31662. if (this._onBindObserver) {
  31663. this.onBindObservable.remove(this._onBindObserver);
  31664. }
  31665. this._onBindObserver = this.onBindObservable.add(callback);
  31666. },
  31667. enumerable: true,
  31668. configurable: true
  31669. });
  31670. Object.defineProperty(Material.prototype, "alphaMode", {
  31671. /**
  31672. * Gets the value of the alpha mode.
  31673. */
  31674. get: function () {
  31675. return this._alphaMode;
  31676. },
  31677. /**
  31678. * Sets the value of the alpha mode.
  31679. *
  31680. * | Value | Type | Description |
  31681. * | --- | --- | --- |
  31682. * | 0 | ALPHA_DISABLE | |
  31683. * | 1 | ALPHA_ADD | |
  31684. * | 2 | ALPHA_COMBINE | |
  31685. * | 3 | ALPHA_SUBTRACT | |
  31686. * | 4 | ALPHA_MULTIPLY | |
  31687. * | 5 | ALPHA_MAXIMIZED | |
  31688. * | 6 | ALPHA_ONEONE | |
  31689. * | 7 | ALPHA_PREMULTIPLIED | |
  31690. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  31691. * | 9 | ALPHA_INTERPOLATE | |
  31692. * | 10 | ALPHA_SCREENMODE | |
  31693. *
  31694. */
  31695. set: function (value) {
  31696. if (this._alphaMode === value) {
  31697. return;
  31698. }
  31699. this._alphaMode = value;
  31700. this.markAsDirty(Material.TextureDirtyFlag);
  31701. },
  31702. enumerable: true,
  31703. configurable: true
  31704. });
  31705. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31706. /**
  31707. * Gets the depth pre-pass value.
  31708. */
  31709. get: function () {
  31710. return this._needDepthPrePass;
  31711. },
  31712. /**
  31713. * Sets the need depth pre-pass value.
  31714. */
  31715. set: function (value) {
  31716. if (this._needDepthPrePass === value) {
  31717. return;
  31718. }
  31719. this._needDepthPrePass = value;
  31720. if (this._needDepthPrePass) {
  31721. this.checkReadyOnEveryCall = true;
  31722. }
  31723. },
  31724. enumerable: true,
  31725. configurable: true
  31726. });
  31727. Object.defineProperty(Material.prototype, "fogEnabled", {
  31728. /**
  31729. * Gets the value of the fog enabled state.
  31730. */
  31731. get: function () {
  31732. return this._fogEnabled;
  31733. },
  31734. /**
  31735. * Sets the state for enabling fog.
  31736. */
  31737. set: function (value) {
  31738. if (this._fogEnabled === value) {
  31739. return;
  31740. }
  31741. this._fogEnabled = value;
  31742. this.markAsDirty(Material.MiscDirtyFlag);
  31743. },
  31744. enumerable: true,
  31745. configurable: true
  31746. });
  31747. Object.defineProperty(Material.prototype, "wireframe", {
  31748. /**
  31749. * Gets a value specifying if wireframe mode is enabled.
  31750. */
  31751. get: function () {
  31752. switch (this._fillMode) {
  31753. case Material.WireFrameFillMode:
  31754. case Material.LineListDrawMode:
  31755. case Material.LineLoopDrawMode:
  31756. case Material.LineStripDrawMode:
  31757. return true;
  31758. }
  31759. return this._scene.forceWireframe;
  31760. },
  31761. /**
  31762. * Sets the state of wireframe mode.
  31763. */
  31764. set: function (value) {
  31765. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31766. },
  31767. enumerable: true,
  31768. configurable: true
  31769. });
  31770. Object.defineProperty(Material.prototype, "pointsCloud", {
  31771. /**
  31772. * Gets the value specifying if point clouds are enabled.
  31773. */
  31774. get: function () {
  31775. switch (this._fillMode) {
  31776. case Material.PointFillMode:
  31777. case Material.PointListDrawMode:
  31778. return true;
  31779. }
  31780. return this._scene.forcePointsCloud;
  31781. },
  31782. /**
  31783. * Sets the state of point cloud mode.
  31784. */
  31785. set: function (value) {
  31786. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31787. },
  31788. enumerable: true,
  31789. configurable: true
  31790. });
  31791. Object.defineProperty(Material.prototype, "fillMode", {
  31792. /**
  31793. * Gets the material fill mode.
  31794. */
  31795. get: function () {
  31796. return this._fillMode;
  31797. },
  31798. /**
  31799. * Sets the material fill mode.
  31800. */
  31801. set: function (value) {
  31802. if (this._fillMode === value) {
  31803. return;
  31804. }
  31805. this._fillMode = value;
  31806. this.markAsDirty(Material.MiscDirtyFlag);
  31807. },
  31808. enumerable: true,
  31809. configurable: true
  31810. });
  31811. /**
  31812. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31813. * subclasses should override adding information pertainent to themselves.
  31814. * @returns - String with material information.
  31815. */
  31816. Material.prototype.toString = function (fullDetails) {
  31817. var ret = "Name: " + this.name;
  31818. if (fullDetails) {
  31819. }
  31820. return ret;
  31821. };
  31822. /**
  31823. * Gets the class name of the material.
  31824. * @returns - String with the class name of the material.
  31825. */
  31826. Material.prototype.getClassName = function () {
  31827. return "Material";
  31828. };
  31829. Object.defineProperty(Material.prototype, "isFrozen", {
  31830. /**
  31831. * Specifies if updates for the material been locked.
  31832. */
  31833. get: function () {
  31834. return this.checkReadyOnlyOnce;
  31835. },
  31836. enumerable: true,
  31837. configurable: true
  31838. });
  31839. /**
  31840. * Locks updates for the material.
  31841. */
  31842. Material.prototype.freeze = function () {
  31843. this.checkReadyOnlyOnce = true;
  31844. };
  31845. /**
  31846. * Unlocks updates for the material.
  31847. */
  31848. Material.prototype.unfreeze = function () {
  31849. this.checkReadyOnlyOnce = false;
  31850. };
  31851. /**
  31852. * Specifies if the material is ready to be used.
  31853. * @param mesh - BJS mesh.
  31854. * @param useInstances - Specifies if instances should be used.
  31855. * @returns - Boolean indicating if the material is ready to be used.
  31856. */
  31857. Material.prototype.isReady = function (mesh, useInstances) {
  31858. return true;
  31859. };
  31860. /**
  31861. * Specifies that the submesh is ready to be used.
  31862. * @param mesh - BJS mesh.
  31863. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31864. * @param useInstances - Specifies that instances should be used.
  31865. * @returns - boolean indicating that the submesh is ready or not.
  31866. */
  31867. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31868. return false;
  31869. };
  31870. /**
  31871. * Returns the material effect.
  31872. * @returns - Nullable material effect.
  31873. */
  31874. Material.prototype.getEffect = function () {
  31875. return this._effect;
  31876. };
  31877. /**
  31878. * Returns the BJS scene.
  31879. * @returns - BJS Scene.
  31880. */
  31881. Material.prototype.getScene = function () {
  31882. return this._scene;
  31883. };
  31884. /**
  31885. * Specifies if the material will require alpha blending
  31886. * @returns - Boolean specifying if alpha blending is needed.
  31887. */
  31888. Material.prototype.needAlphaBlending = function () {
  31889. return (this.alpha < 1.0);
  31890. };
  31891. /**
  31892. * Specifies if the mesh will require alpha blending.
  31893. * @param mesh - BJS mesh.
  31894. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31895. */
  31896. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31897. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31898. };
  31899. /**
  31900. * Specifies if this material should be rendered in alpha test mode.
  31901. * @returns - Boolean specifying if an alpha test is needed.
  31902. */
  31903. Material.prototype.needAlphaTesting = function () {
  31904. return false;
  31905. };
  31906. /**
  31907. * Gets the texture used for the alpha test.
  31908. * @returns - Nullable alpha test texture.
  31909. */
  31910. Material.prototype.getAlphaTestTexture = function () {
  31911. return null;
  31912. };
  31913. /**
  31914. * Marks the material to indicate that it needs to be re-calculated.
  31915. */
  31916. Material.prototype.markDirty = function () {
  31917. this._wasPreviouslyReady = false;
  31918. };
  31919. Material.prototype._preBind = function (effect, overrideOrientation) {
  31920. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31921. var engine = this._scene.getEngine();
  31922. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31923. var reverse = orientation === Material.ClockWiseSideOrientation;
  31924. engine.enableEffect(effect ? effect : this._effect);
  31925. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31926. return reverse;
  31927. };
  31928. /**
  31929. * Binds the material to the mesh.
  31930. * @param world - World transformation matrix.
  31931. * @param mesh - Mesh to bind the material to.
  31932. */
  31933. Material.prototype.bind = function (world, mesh) {
  31934. };
  31935. /**
  31936. * Binds the submesh to the material.
  31937. * @param world - World transformation matrix.
  31938. * @param mesh - Mesh containing the submesh.
  31939. * @param subMesh - Submesh to bind the material to.
  31940. */
  31941. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31942. };
  31943. /**
  31944. * Binds the world matrix to the material.
  31945. * @param world - World transformation matrix.
  31946. */
  31947. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31948. };
  31949. /**
  31950. * Binds the scene's uniform buffer to the effect.
  31951. * @param effect - Effect to bind to the scene uniform buffer.
  31952. * @param sceneUbo - Scene uniform buffer.
  31953. */
  31954. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31955. sceneUbo.bindToEffect(effect, "Scene");
  31956. };
  31957. /**
  31958. * Binds the view matrix to the effect.
  31959. * @param effect - Effect to bind the view matrix to.
  31960. */
  31961. Material.prototype.bindView = function (effect) {
  31962. if (!this._useUBO) {
  31963. effect.setMatrix("view", this.getScene().getViewMatrix());
  31964. }
  31965. else {
  31966. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31967. }
  31968. };
  31969. /**
  31970. * Binds the view projection matrix to the effect.
  31971. * @param effect - Effect to bind the view projection matrix to.
  31972. */
  31973. Material.prototype.bindViewProjection = function (effect) {
  31974. if (!this._useUBO) {
  31975. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31976. }
  31977. else {
  31978. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31979. }
  31980. };
  31981. /**
  31982. * Specifies if material alpha testing should be turned on for the mesh.
  31983. * @param mesh - BJS mesh.
  31984. */
  31985. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31986. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31987. };
  31988. /**
  31989. * Processes to execute after binding the material to a mesh.
  31990. * @param mesh - BJS mesh.
  31991. */
  31992. Material.prototype._afterBind = function (mesh) {
  31993. this._scene._cachedMaterial = this;
  31994. if (mesh) {
  31995. this._scene._cachedVisibility = mesh.visibility;
  31996. }
  31997. else {
  31998. this._scene._cachedVisibility = 1;
  31999. }
  32000. if (mesh) {
  32001. this.onBindObservable.notifyObservers(mesh);
  32002. }
  32003. if (this.disableDepthWrite) {
  32004. var engine = this._scene.getEngine();
  32005. this._cachedDepthWriteState = engine.getDepthWrite();
  32006. engine.setDepthWrite(false);
  32007. }
  32008. };
  32009. /**
  32010. * Unbinds the material from the mesh.
  32011. */
  32012. Material.prototype.unbind = function () {
  32013. this.onUnBindObservable.notifyObservers(this);
  32014. if (this.disableDepthWrite) {
  32015. var engine = this._scene.getEngine();
  32016. engine.setDepthWrite(this._cachedDepthWriteState);
  32017. }
  32018. };
  32019. /**
  32020. * Gets the active textures from the material.
  32021. * @returns - Array of textures.
  32022. */
  32023. Material.prototype.getActiveTextures = function () {
  32024. return [];
  32025. };
  32026. /**
  32027. * Specifies if the material uses a texture.
  32028. * @param texture - Texture to check against the material.
  32029. * @returns - Boolean specifying if the material uses the texture.
  32030. */
  32031. Material.prototype.hasTexture = function (texture) {
  32032. return false;
  32033. };
  32034. /**
  32035. * Makes a duplicate of the material, and gives it a new name.
  32036. * @param name - Name to call the duplicated material.
  32037. * @returns - Nullable cloned material
  32038. */
  32039. Material.prototype.clone = function (name) {
  32040. return null;
  32041. };
  32042. /**
  32043. * Gets the meshes bound to the material.
  32044. * @returns - Array of meshes bound to the material.
  32045. */
  32046. Material.prototype.getBindedMeshes = function () {
  32047. var result = new Array();
  32048. for (var index = 0; index < this._scene.meshes.length; index++) {
  32049. var mesh = this._scene.meshes[index];
  32050. if (mesh.material === this) {
  32051. result.push(mesh);
  32052. }
  32053. }
  32054. return result;
  32055. };
  32056. /**
  32057. * Force shader compilation
  32058. * @param mesh - BJS mesh.
  32059. * @param onCompiled - function to execute once the material is compiled.
  32060. * @param options - options to pass to this function.
  32061. */
  32062. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32063. var _this = this;
  32064. var localOptions = __assign({ clipPlane: false }, options);
  32065. var subMesh = new BABYLON.BaseSubMesh();
  32066. var scene = this.getScene();
  32067. var checkReady = function () {
  32068. if (!_this._scene || !_this._scene.getEngine()) {
  32069. return;
  32070. }
  32071. if (subMesh._materialDefines) {
  32072. subMesh._materialDefines._renderId = -1;
  32073. }
  32074. var clipPlaneState = scene.clipPlane;
  32075. if (localOptions.clipPlane) {
  32076. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32077. }
  32078. if (_this.storeEffectOnSubMeshes) {
  32079. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32080. if (onCompiled) {
  32081. onCompiled(_this);
  32082. }
  32083. }
  32084. else {
  32085. setTimeout(checkReady, 16);
  32086. }
  32087. }
  32088. else {
  32089. if (_this.isReady(mesh)) {
  32090. if (onCompiled) {
  32091. onCompiled(_this);
  32092. }
  32093. }
  32094. else {
  32095. setTimeout(checkReady, 16);
  32096. }
  32097. }
  32098. if (localOptions.clipPlane) {
  32099. scene.clipPlane = clipPlaneState;
  32100. }
  32101. };
  32102. checkReady();
  32103. };
  32104. /**
  32105. * Force shader compilation.
  32106. * @param mesh The mesh that will use this material
  32107. * @param options Additional options for compiling the shaders
  32108. * @returns A promise that resolves when the compilation completes
  32109. */
  32110. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32111. var _this = this;
  32112. return new Promise(function (resolve) {
  32113. _this.forceCompilation(mesh, function () {
  32114. resolve();
  32115. }, options);
  32116. });
  32117. };
  32118. /**
  32119. * Marks a define in the material to indicate that it needs to be re-computed.
  32120. * @param flag - Material define flag.
  32121. */
  32122. Material.prototype.markAsDirty = function (flag) {
  32123. if (flag & Material.TextureDirtyFlag) {
  32124. this._markAllSubMeshesAsTexturesDirty();
  32125. }
  32126. if (flag & Material.LightDirtyFlag) {
  32127. this._markAllSubMeshesAsLightsDirty();
  32128. }
  32129. if (flag & Material.FresnelDirtyFlag) {
  32130. this._markAllSubMeshesAsFresnelDirty();
  32131. }
  32132. if (flag & Material.AttributesDirtyFlag) {
  32133. this._markAllSubMeshesAsAttributesDirty();
  32134. }
  32135. if (flag & Material.MiscDirtyFlag) {
  32136. this._markAllSubMeshesAsMiscDirty();
  32137. }
  32138. this.getScene().resetCachedMaterial();
  32139. };
  32140. /**
  32141. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32142. * @param func - function which checks material defines against the submeshes.
  32143. */
  32144. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32145. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32146. var mesh = _a[_i];
  32147. if (!mesh.subMeshes) {
  32148. continue;
  32149. }
  32150. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32151. var subMesh = _c[_b];
  32152. if (subMesh.getMaterial() !== this) {
  32153. continue;
  32154. }
  32155. if (!subMesh._materialDefines) {
  32156. continue;
  32157. }
  32158. func(subMesh._materialDefines);
  32159. }
  32160. }
  32161. };
  32162. /**
  32163. * Indicates that image processing needs to be re-calculated for all submeshes.
  32164. */
  32165. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32166. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32167. };
  32168. /**
  32169. * Indicates that textures need to be re-calculated for all submeshes.
  32170. */
  32171. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32172. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32173. };
  32174. /**
  32175. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32176. */
  32177. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32178. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32179. };
  32180. /**
  32181. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32182. */
  32183. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32184. this._markAllSubMeshesAsDirty(function (defines) {
  32185. defines.markAsFresnelDirty();
  32186. defines.markAsMiscDirty();
  32187. });
  32188. };
  32189. /**
  32190. * Indicates that lights need to be re-calculated for all submeshes.
  32191. */
  32192. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32193. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32194. };
  32195. /**
  32196. * Indicates that attributes need to be re-calculated for all submeshes.
  32197. */
  32198. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32199. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32200. };
  32201. /**
  32202. * Indicates that misc needs to be re-calculated for all submeshes.
  32203. */
  32204. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32205. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32206. };
  32207. /**
  32208. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32209. */
  32210. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32211. this._markAllSubMeshesAsDirty(function (defines) {
  32212. defines.markAsTexturesDirty();
  32213. defines.markAsMiscDirty();
  32214. });
  32215. };
  32216. /**
  32217. * Disposes the material.
  32218. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32219. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32220. */
  32221. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32222. // Animations
  32223. this.getScene().stopAnimation(this);
  32224. this.getScene().freeProcessedMaterials();
  32225. // Remove from scene
  32226. var index = this._scene.materials.indexOf(this);
  32227. if (index >= 0) {
  32228. this._scene.materials.splice(index, 1);
  32229. }
  32230. // Remove from meshes
  32231. for (index = 0; index < this._scene.meshes.length; index++) {
  32232. var mesh = this._scene.meshes[index];
  32233. if (mesh.material === this) {
  32234. mesh.material = null;
  32235. if (mesh.geometry) {
  32236. var geometry = (mesh.geometry);
  32237. if (this.storeEffectOnSubMeshes) {
  32238. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32239. var subMesh = _a[_i];
  32240. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32241. if (forceDisposeEffect && subMesh._materialEffect) {
  32242. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32243. }
  32244. }
  32245. }
  32246. else {
  32247. geometry._releaseVertexArrayObject(this._effect);
  32248. }
  32249. }
  32250. }
  32251. }
  32252. this._uniformBuffer.dispose();
  32253. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32254. if (forceDisposeEffect && this._effect) {
  32255. if (!this.storeEffectOnSubMeshes) {
  32256. this._scene.getEngine()._releaseEffect(this._effect);
  32257. }
  32258. this._effect = null;
  32259. }
  32260. // Callback
  32261. this.onDisposeObservable.notifyObservers(this);
  32262. this.onDisposeObservable.clear();
  32263. this.onBindObservable.clear();
  32264. this.onUnBindObservable.clear();
  32265. };
  32266. /**
  32267. * Serializes this material.
  32268. * @returns - serialized material object.
  32269. */
  32270. Material.prototype.serialize = function () {
  32271. return BABYLON.SerializationHelper.Serialize(this);
  32272. };
  32273. /**
  32274. * Creates a MultiMaterial from parse MultiMaterial data.
  32275. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32276. * @param scene - BJS scene.
  32277. * @returns - MultiMaterial.
  32278. */
  32279. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32280. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32281. multiMaterial.id = parsedMultiMaterial.id;
  32282. if (BABYLON.Tags) {
  32283. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32284. }
  32285. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32286. var subMatId = parsedMultiMaterial.materials[matIndex];
  32287. if (subMatId) {
  32288. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32289. }
  32290. else {
  32291. multiMaterial.subMaterials.push(null);
  32292. }
  32293. }
  32294. return multiMaterial;
  32295. };
  32296. /**
  32297. * Creates a material from parsed material data.
  32298. * @param parsedMaterial - Parsed material data.
  32299. * @param scene - BJS scene.
  32300. * @param rootUrl - Root URL containing the material information.
  32301. * @returns - Parsed material.
  32302. */
  32303. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32304. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32305. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32306. }
  32307. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32308. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32309. if (!BABYLON.LegacyPBRMaterial) {
  32310. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32311. return;
  32312. }
  32313. }
  32314. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32315. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32316. ;
  32317. };
  32318. // Triangle views
  32319. Material._TriangleFillMode = 0;
  32320. Material._WireFrameFillMode = 1;
  32321. Material._PointFillMode = 2;
  32322. // Draw modes
  32323. Material._PointListDrawMode = 3;
  32324. Material._LineListDrawMode = 4;
  32325. Material._LineLoopDrawMode = 5;
  32326. Material._LineStripDrawMode = 6;
  32327. Material._TriangleStripDrawMode = 7;
  32328. Material._TriangleFanDrawMode = 8;
  32329. /**
  32330. * Stores the clock-wise side orientation.
  32331. */
  32332. Material._ClockWiseSideOrientation = 0;
  32333. /**
  32334. * Stores the counter clock-wise side orientation.
  32335. */
  32336. Material._CounterClockWiseSideOrientation = 1;
  32337. /**
  32338. * The dirty texture flag value.
  32339. */
  32340. Material._TextureDirtyFlag = 1;
  32341. /**
  32342. * The dirty light flag value.
  32343. */
  32344. Material._LightDirtyFlag = 2;
  32345. /**
  32346. * The dirty fresnel flag value.
  32347. */
  32348. Material._FresnelDirtyFlag = 4;
  32349. /**
  32350. * The dirty attribute flag value.
  32351. */
  32352. Material._AttributesDirtyFlag = 8;
  32353. /**
  32354. * The dirty misc flag value.
  32355. */
  32356. Material._MiscDirtyFlag = 16;
  32357. __decorate([
  32358. BABYLON.serialize()
  32359. ], Material.prototype, "id", void 0);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], Material.prototype, "name", void 0);
  32363. __decorate([
  32364. BABYLON.serialize()
  32365. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32366. __decorate([
  32367. BABYLON.serialize()
  32368. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], Material.prototype, "state", void 0);
  32372. __decorate([
  32373. BABYLON.serialize("alpha")
  32374. ], Material.prototype, "_alpha", void 0);
  32375. __decorate([
  32376. BABYLON.serialize("backFaceCulling")
  32377. ], Material.prototype, "_backFaceCulling", void 0);
  32378. __decorate([
  32379. BABYLON.serialize()
  32380. ], Material.prototype, "sideOrientation", void 0);
  32381. __decorate([
  32382. BABYLON.serialize("alphaMode")
  32383. ], Material.prototype, "_alphaMode", void 0);
  32384. __decorate([
  32385. BABYLON.serialize()
  32386. ], Material.prototype, "_needDepthPrePass", void 0);
  32387. __decorate([
  32388. BABYLON.serialize()
  32389. ], Material.prototype, "disableDepthWrite", void 0);
  32390. __decorate([
  32391. BABYLON.serialize()
  32392. ], Material.prototype, "forceDepthWrite", void 0);
  32393. __decorate([
  32394. BABYLON.serialize()
  32395. ], Material.prototype, "separateCullingPass", void 0);
  32396. __decorate([
  32397. BABYLON.serialize("fogEnabled")
  32398. ], Material.prototype, "_fogEnabled", void 0);
  32399. __decorate([
  32400. BABYLON.serialize()
  32401. ], Material.prototype, "pointSize", void 0);
  32402. __decorate([
  32403. BABYLON.serialize()
  32404. ], Material.prototype, "zOffset", void 0);
  32405. __decorate([
  32406. BABYLON.serialize()
  32407. ], Material.prototype, "wireframe", null);
  32408. __decorate([
  32409. BABYLON.serialize()
  32410. ], Material.prototype, "pointsCloud", null);
  32411. __decorate([
  32412. BABYLON.serialize()
  32413. ], Material.prototype, "fillMode", null);
  32414. return Material;
  32415. }());
  32416. BABYLON.Material = Material;
  32417. })(BABYLON || (BABYLON = {}));
  32418. //# sourceMappingURL=babylon.material.js.map
  32419. "use strict";
  32420. var BABYLON;
  32421. (function (BABYLON) {
  32422. var UniformBuffer = /** @class */ (function () {
  32423. /**
  32424. * Uniform buffer objects.
  32425. *
  32426. * Handles blocks of uniform on the GPU.
  32427. *
  32428. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32429. *
  32430. * For more information, please refer to :
  32431. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32432. */
  32433. function UniformBuffer(engine, data, dynamic) {
  32434. this._engine = engine;
  32435. this._noUBO = !engine.supportsUniformBuffers;
  32436. this._dynamic = dynamic;
  32437. this._data = data || [];
  32438. this._uniformLocations = {};
  32439. this._uniformSizes = {};
  32440. this._uniformLocationPointer = 0;
  32441. this._needSync = false;
  32442. if (this._noUBO) {
  32443. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32444. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32445. this.updateFloat = this._updateFloatForEffect;
  32446. this.updateFloat2 = this._updateFloat2ForEffect;
  32447. this.updateFloat3 = this._updateFloat3ForEffect;
  32448. this.updateFloat4 = this._updateFloat4ForEffect;
  32449. this.updateMatrix = this._updateMatrixForEffect;
  32450. this.updateVector3 = this._updateVector3ForEffect;
  32451. this.updateVector4 = this._updateVector4ForEffect;
  32452. this.updateColor3 = this._updateColor3ForEffect;
  32453. this.updateColor4 = this._updateColor4ForEffect;
  32454. }
  32455. else {
  32456. this._engine._uniformBuffers.push(this);
  32457. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32458. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32459. this.updateFloat = this._updateFloatForUniform;
  32460. this.updateFloat2 = this._updateFloat2ForUniform;
  32461. this.updateFloat3 = this._updateFloat3ForUniform;
  32462. this.updateFloat4 = this._updateFloat4ForUniform;
  32463. this.updateMatrix = this._updateMatrixForUniform;
  32464. this.updateVector3 = this._updateVector3ForUniform;
  32465. this.updateVector4 = this._updateVector4ForUniform;
  32466. this.updateColor3 = this._updateColor3ForUniform;
  32467. this.updateColor4 = this._updateColor4ForUniform;
  32468. }
  32469. }
  32470. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32471. // Properties
  32472. /**
  32473. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32474. * or just falling back on setUniformXXX calls.
  32475. */
  32476. get: function () {
  32477. return !this._noUBO;
  32478. },
  32479. enumerable: true,
  32480. configurable: true
  32481. });
  32482. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32483. /**
  32484. * Indicates if the WebGL underlying uniform buffer is in sync
  32485. * with the javascript cache data.
  32486. */
  32487. get: function () {
  32488. return !this._needSync;
  32489. },
  32490. enumerable: true,
  32491. configurable: true
  32492. });
  32493. /**
  32494. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32495. * Also, a dynamic UniformBuffer will disable cache verification and always
  32496. * update the underlying WebGL uniform buffer to the GPU.
  32497. */
  32498. UniformBuffer.prototype.isDynamic = function () {
  32499. return this._dynamic !== undefined;
  32500. };
  32501. /**
  32502. * The data cache on JS side.
  32503. */
  32504. UniformBuffer.prototype.getData = function () {
  32505. return this._bufferData;
  32506. };
  32507. /**
  32508. * The underlying WebGL Uniform buffer.
  32509. */
  32510. UniformBuffer.prototype.getBuffer = function () {
  32511. return this._buffer;
  32512. };
  32513. /**
  32514. * std140 layout specifies how to align data within an UBO structure.
  32515. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32516. * for specs.
  32517. */
  32518. UniformBuffer.prototype._fillAlignment = function (size) {
  32519. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32520. // and 4x4 matrices
  32521. // TODO : change if other types are used
  32522. var alignment;
  32523. if (size <= 2) {
  32524. alignment = size;
  32525. }
  32526. else {
  32527. alignment = 4;
  32528. }
  32529. if ((this._uniformLocationPointer % alignment) !== 0) {
  32530. var oldPointer = this._uniformLocationPointer;
  32531. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32532. var diff = this._uniformLocationPointer - oldPointer;
  32533. for (var i = 0; i < diff; i++) {
  32534. this._data.push(0);
  32535. }
  32536. }
  32537. };
  32538. /**
  32539. * Adds an uniform in the buffer.
  32540. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32541. * for the layout to be correct !
  32542. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32543. * @param {number|number[]} size Data size, or data directly.
  32544. */
  32545. UniformBuffer.prototype.addUniform = function (name, size) {
  32546. if (this._noUBO) {
  32547. return;
  32548. }
  32549. if (this._uniformLocations[name] !== undefined) {
  32550. // Already existing uniform
  32551. return;
  32552. }
  32553. // This function must be called in the order of the shader layout !
  32554. // size can be the size of the uniform, or data directly
  32555. var data;
  32556. if (size instanceof Array) {
  32557. data = size;
  32558. size = data.length;
  32559. }
  32560. else {
  32561. size = size;
  32562. data = [];
  32563. // Fill with zeros
  32564. for (var i = 0; i < size; i++) {
  32565. data.push(0);
  32566. }
  32567. }
  32568. this._fillAlignment(size);
  32569. this._uniformSizes[name] = size;
  32570. this._uniformLocations[name] = this._uniformLocationPointer;
  32571. this._uniformLocationPointer += size;
  32572. for (var i = 0; i < size; i++) {
  32573. this._data.push(data[i]);
  32574. }
  32575. this._needSync = true;
  32576. };
  32577. /**
  32578. * Wrapper for addUniform.
  32579. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32580. * @param {Matrix} mat A 4x4 matrix.
  32581. */
  32582. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32583. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32584. };
  32585. /**
  32586. * Wrapper for addUniform.
  32587. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32588. * @param {number} x
  32589. * @param {number} y
  32590. */
  32591. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32592. var temp = [x, y];
  32593. this.addUniform(name, temp);
  32594. };
  32595. /**
  32596. * Wrapper for addUniform.
  32597. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32598. * @param {number} x
  32599. * @param {number} y
  32600. * @param {number} z
  32601. */
  32602. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32603. var temp = [x, y, z];
  32604. this.addUniform(name, temp);
  32605. };
  32606. /**
  32607. * Wrapper for addUniform.
  32608. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32609. * @param {Color3} color
  32610. */
  32611. UniformBuffer.prototype.addColor3 = function (name, color) {
  32612. var temp = new Array();
  32613. color.toArray(temp);
  32614. this.addUniform(name, temp);
  32615. };
  32616. /**
  32617. * Wrapper for addUniform.
  32618. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32619. * @param {Color3} color
  32620. * @param {number} alpha
  32621. */
  32622. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32623. var temp = new Array();
  32624. color.toArray(temp);
  32625. temp.push(alpha);
  32626. this.addUniform(name, temp);
  32627. };
  32628. /**
  32629. * Wrapper for addUniform.
  32630. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32631. * @param {Vector3} vector
  32632. */
  32633. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32634. var temp = new Array();
  32635. vector.toArray(temp);
  32636. this.addUniform(name, temp);
  32637. };
  32638. /**
  32639. * Wrapper for addUniform.
  32640. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32641. */
  32642. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32643. this.addUniform(name, 12);
  32644. };
  32645. /**
  32646. * Wrapper for addUniform.
  32647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32648. */
  32649. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32650. this.addUniform(name, 8);
  32651. };
  32652. /**
  32653. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32654. */
  32655. UniformBuffer.prototype.create = function () {
  32656. if (this._noUBO) {
  32657. return;
  32658. }
  32659. if (this._buffer) {
  32660. return; // nothing to do
  32661. }
  32662. // See spec, alignment must be filled as a vec4
  32663. this._fillAlignment(4);
  32664. this._bufferData = new Float32Array(this._data);
  32665. this._rebuild();
  32666. this._needSync = true;
  32667. };
  32668. UniformBuffer.prototype._rebuild = function () {
  32669. if (this._noUBO) {
  32670. return;
  32671. }
  32672. if (this._dynamic) {
  32673. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32674. }
  32675. else {
  32676. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32677. }
  32678. };
  32679. /**
  32680. * Updates the WebGL Uniform Buffer on the GPU.
  32681. * If the `dynamic` flag is set to true, no cache comparison is done.
  32682. * Otherwise, the buffer will be updated only if the cache differs.
  32683. */
  32684. UniformBuffer.prototype.update = function () {
  32685. if (!this._buffer) {
  32686. this.create();
  32687. return;
  32688. }
  32689. if (!this._dynamic && !this._needSync) {
  32690. return;
  32691. }
  32692. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32693. this._needSync = false;
  32694. };
  32695. /**
  32696. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32697. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32698. * @param {number[]|Float32Array} data Flattened data
  32699. * @param {number} size Size of the data.
  32700. */
  32701. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32702. var location = this._uniformLocations[uniformName];
  32703. if (location === undefined) {
  32704. if (this._buffer) {
  32705. // Cannot add an uniform if the buffer is already created
  32706. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32707. return;
  32708. }
  32709. this.addUniform(uniformName, size);
  32710. location = this._uniformLocations[uniformName];
  32711. }
  32712. if (!this._buffer) {
  32713. this.create();
  32714. }
  32715. if (!this._dynamic) {
  32716. // Cache for static uniform buffers
  32717. var changed = false;
  32718. for (var i = 0; i < size; i++) {
  32719. if (this._bufferData[location + i] !== data[i]) {
  32720. changed = true;
  32721. this._bufferData[location + i] = data[i];
  32722. }
  32723. }
  32724. this._needSync = this._needSync || changed;
  32725. }
  32726. else {
  32727. // No cache for dynamic
  32728. for (var i = 0; i < size; i++) {
  32729. this._bufferData[location + i] = data[i];
  32730. }
  32731. }
  32732. };
  32733. // Update methods
  32734. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32735. // To match std140, matrix must be realigned
  32736. for (var i = 0; i < 3; i++) {
  32737. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32738. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32739. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32740. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32741. }
  32742. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32743. };
  32744. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32745. this._currentEffect.setMatrix3x3(name, matrix);
  32746. };
  32747. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32748. this._currentEffect.setMatrix2x2(name, matrix);
  32749. };
  32750. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32751. // To match std140, matrix must be realigned
  32752. for (var i = 0; i < 2; i++) {
  32753. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32754. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32755. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32756. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32757. }
  32758. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32759. };
  32760. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32761. this._currentEffect.setFloat(name, x);
  32762. };
  32763. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32764. UniformBuffer._tempBuffer[0] = x;
  32765. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32766. };
  32767. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32768. if (suffix === void 0) { suffix = ""; }
  32769. this._currentEffect.setFloat2(name + suffix, x, y);
  32770. };
  32771. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32772. if (suffix === void 0) { suffix = ""; }
  32773. UniformBuffer._tempBuffer[0] = x;
  32774. UniformBuffer._tempBuffer[1] = y;
  32775. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32776. };
  32777. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32778. if (suffix === void 0) { suffix = ""; }
  32779. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32780. };
  32781. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32782. if (suffix === void 0) { suffix = ""; }
  32783. UniformBuffer._tempBuffer[0] = x;
  32784. UniformBuffer._tempBuffer[1] = y;
  32785. UniformBuffer._tempBuffer[2] = z;
  32786. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32787. };
  32788. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32789. if (suffix === void 0) { suffix = ""; }
  32790. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32791. };
  32792. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32793. if (suffix === void 0) { suffix = ""; }
  32794. UniformBuffer._tempBuffer[0] = x;
  32795. UniformBuffer._tempBuffer[1] = y;
  32796. UniformBuffer._tempBuffer[2] = z;
  32797. UniformBuffer._tempBuffer[3] = w;
  32798. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32799. };
  32800. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32801. this._currentEffect.setMatrix(name, mat);
  32802. };
  32803. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32804. this.updateUniform(name, mat.toArray(), 16);
  32805. };
  32806. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32807. this._currentEffect.setVector3(name, vector);
  32808. };
  32809. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32810. vector.toArray(UniformBuffer._tempBuffer);
  32811. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32812. };
  32813. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32814. this._currentEffect.setVector4(name, vector);
  32815. };
  32816. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32817. vector.toArray(UniformBuffer._tempBuffer);
  32818. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32819. };
  32820. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32821. if (suffix === void 0) { suffix = ""; }
  32822. this._currentEffect.setColor3(name + suffix, color);
  32823. };
  32824. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32825. if (suffix === void 0) { suffix = ""; }
  32826. color.toArray(UniformBuffer._tempBuffer);
  32827. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32828. };
  32829. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32830. if (suffix === void 0) { suffix = ""; }
  32831. this._currentEffect.setColor4(name + suffix, color, alpha);
  32832. };
  32833. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32834. if (suffix === void 0) { suffix = ""; }
  32835. color.toArray(UniformBuffer._tempBuffer);
  32836. UniformBuffer._tempBuffer[3] = alpha;
  32837. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32838. };
  32839. /**
  32840. * Sets a sampler uniform on the effect.
  32841. * @param {string} name Name of the sampler.
  32842. * @param {Texture} texture
  32843. */
  32844. UniformBuffer.prototype.setTexture = function (name, texture) {
  32845. this._currentEffect.setTexture(name, texture);
  32846. };
  32847. /**
  32848. * Directly updates the value of the uniform in the cache AND on the GPU.
  32849. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32850. * @param {number[]|Float32Array} data Flattened data
  32851. */
  32852. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32853. this.updateUniform(uniformName, data, data.length);
  32854. this.update();
  32855. };
  32856. /**
  32857. * Binds this uniform buffer to an effect.
  32858. * @param {Effect} effect
  32859. * @param {string} name Name of the uniform block in the shader.
  32860. */
  32861. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32862. this._currentEffect = effect;
  32863. if (this._noUBO || !this._buffer) {
  32864. return;
  32865. }
  32866. effect.bindUniformBuffer(this._buffer, name);
  32867. };
  32868. /**
  32869. * Disposes the uniform buffer.
  32870. */
  32871. UniformBuffer.prototype.dispose = function () {
  32872. if (this._noUBO) {
  32873. return;
  32874. }
  32875. var index = this._engine._uniformBuffers.indexOf(this);
  32876. if (index !== -1) {
  32877. this._engine._uniformBuffers.splice(index, 1);
  32878. }
  32879. if (!this._buffer) {
  32880. return;
  32881. }
  32882. if (this._engine._releaseBuffer(this._buffer)) {
  32883. this._buffer = null;
  32884. }
  32885. };
  32886. // Pool for avoiding memory leaks
  32887. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32888. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32889. return UniformBuffer;
  32890. }());
  32891. BABYLON.UniformBuffer = UniformBuffer;
  32892. })(BABYLON || (BABYLON = {}));
  32893. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32894. "use strict";
  32895. var BABYLON;
  32896. (function (BABYLON) {
  32897. var VertexData = /** @class */ (function () {
  32898. function VertexData() {
  32899. }
  32900. VertexData.prototype.set = function (data, kind) {
  32901. switch (kind) {
  32902. case BABYLON.VertexBuffer.PositionKind:
  32903. this.positions = data;
  32904. break;
  32905. case BABYLON.VertexBuffer.NormalKind:
  32906. this.normals = data;
  32907. break;
  32908. case BABYLON.VertexBuffer.TangentKind:
  32909. this.tangents = data;
  32910. break;
  32911. case BABYLON.VertexBuffer.UVKind:
  32912. this.uvs = data;
  32913. break;
  32914. case BABYLON.VertexBuffer.UV2Kind:
  32915. this.uvs2 = data;
  32916. break;
  32917. case BABYLON.VertexBuffer.UV3Kind:
  32918. this.uvs3 = data;
  32919. break;
  32920. case BABYLON.VertexBuffer.UV4Kind:
  32921. this.uvs4 = data;
  32922. break;
  32923. case BABYLON.VertexBuffer.UV5Kind:
  32924. this.uvs5 = data;
  32925. break;
  32926. case BABYLON.VertexBuffer.UV6Kind:
  32927. this.uvs6 = data;
  32928. break;
  32929. case BABYLON.VertexBuffer.ColorKind:
  32930. this.colors = data;
  32931. break;
  32932. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32933. this.matricesIndices = data;
  32934. break;
  32935. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32936. this.matricesWeights = data;
  32937. break;
  32938. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32939. this.matricesIndicesExtra = data;
  32940. break;
  32941. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32942. this.matricesWeightsExtra = data;
  32943. break;
  32944. }
  32945. };
  32946. /**
  32947. * Associates the vertexData to the passed Mesh.
  32948. * Sets it as updatable or not (default `false`).
  32949. * Returns the VertexData.
  32950. */
  32951. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32952. this._applyTo(mesh, updatable);
  32953. return this;
  32954. };
  32955. /**
  32956. * Associates the vertexData to the passed Geometry.
  32957. * Sets it as updatable or not (default `false`).
  32958. * Returns the VertexData.
  32959. */
  32960. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32961. this._applyTo(geometry, updatable);
  32962. return this;
  32963. };
  32964. /**
  32965. * Updates the associated mesh.
  32966. * Returns the VertexData.
  32967. */
  32968. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32969. this._update(mesh);
  32970. return this;
  32971. };
  32972. /**
  32973. * Updates the associated geometry.
  32974. * Returns the VertexData.
  32975. */
  32976. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32977. this._update(geometry);
  32978. return this;
  32979. };
  32980. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32981. if (updatable === void 0) { updatable = false; }
  32982. if (this.positions) {
  32983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32984. }
  32985. if (this.normals) {
  32986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32987. }
  32988. if (this.tangents) {
  32989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32990. }
  32991. if (this.uvs) {
  32992. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32993. }
  32994. if (this.uvs2) {
  32995. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32996. }
  32997. if (this.uvs3) {
  32998. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32999. }
  33000. if (this.uvs4) {
  33001. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33002. }
  33003. if (this.uvs5) {
  33004. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33005. }
  33006. if (this.uvs6) {
  33007. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33008. }
  33009. if (this.colors) {
  33010. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33011. }
  33012. if (this.matricesIndices) {
  33013. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33014. }
  33015. if (this.matricesWeights) {
  33016. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33017. }
  33018. if (this.matricesIndicesExtra) {
  33019. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33020. }
  33021. if (this.matricesWeightsExtra) {
  33022. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33023. }
  33024. if (this.indices) {
  33025. meshOrGeometry.setIndices(this.indices, null, updatable);
  33026. }
  33027. return this;
  33028. };
  33029. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33030. if (this.positions) {
  33031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33032. }
  33033. if (this.normals) {
  33034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33035. }
  33036. if (this.tangents) {
  33037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33038. }
  33039. if (this.uvs) {
  33040. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33041. }
  33042. if (this.uvs2) {
  33043. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33044. }
  33045. if (this.uvs3) {
  33046. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33047. }
  33048. if (this.uvs4) {
  33049. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33050. }
  33051. if (this.uvs5) {
  33052. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33053. }
  33054. if (this.uvs6) {
  33055. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33056. }
  33057. if (this.colors) {
  33058. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33059. }
  33060. if (this.matricesIndices) {
  33061. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33062. }
  33063. if (this.matricesWeights) {
  33064. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33065. }
  33066. if (this.matricesIndicesExtra) {
  33067. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33068. }
  33069. if (this.matricesWeightsExtra) {
  33070. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33071. }
  33072. if (this.indices) {
  33073. meshOrGeometry.setIndices(this.indices, null);
  33074. }
  33075. return this;
  33076. };
  33077. /**
  33078. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33079. * Returns the VertexData.
  33080. */
  33081. VertexData.prototype.transform = function (matrix) {
  33082. var transformed = BABYLON.Vector3.Zero();
  33083. var index;
  33084. if (this.positions) {
  33085. var position = BABYLON.Vector3.Zero();
  33086. for (index = 0; index < this.positions.length; index += 3) {
  33087. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33088. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33089. this.positions[index] = transformed.x;
  33090. this.positions[index + 1] = transformed.y;
  33091. this.positions[index + 2] = transformed.z;
  33092. }
  33093. }
  33094. if (this.normals) {
  33095. var normal = BABYLON.Vector3.Zero();
  33096. for (index = 0; index < this.normals.length; index += 3) {
  33097. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33098. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33099. this.normals[index] = transformed.x;
  33100. this.normals[index + 1] = transformed.y;
  33101. this.normals[index + 2] = transformed.z;
  33102. }
  33103. }
  33104. if (this.tangents) {
  33105. var tangent = BABYLON.Vector4.Zero();
  33106. var tangentTransformed = BABYLON.Vector4.Zero();
  33107. for (index = 0; index < this.tangents.length; index += 4) {
  33108. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33109. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33110. this.tangents[index] = tangentTransformed.x;
  33111. this.tangents[index + 1] = tangentTransformed.y;
  33112. this.tangents[index + 2] = tangentTransformed.z;
  33113. this.tangents[index + 3] = tangentTransformed.w;
  33114. }
  33115. }
  33116. return this;
  33117. };
  33118. /**
  33119. * Merges the passed VertexData into the current one.
  33120. * Returns the modified VertexData.
  33121. */
  33122. VertexData.prototype.merge = function (other) {
  33123. this._validate();
  33124. other._validate();
  33125. if (!this.normals !== !other.normals ||
  33126. !this.tangents !== !other.tangents ||
  33127. !this.uvs !== !other.uvs ||
  33128. !this.uvs2 !== !other.uvs2 ||
  33129. !this.uvs3 !== !other.uvs3 ||
  33130. !this.uvs4 !== !other.uvs4 ||
  33131. !this.uvs5 !== !other.uvs5 ||
  33132. !this.uvs6 !== !other.uvs6 ||
  33133. !this.colors !== !other.colors ||
  33134. !this.matricesIndices !== !other.matricesIndices ||
  33135. !this.matricesWeights !== !other.matricesWeights ||
  33136. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33137. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33138. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33139. }
  33140. if (other.indices) {
  33141. if (!this.indices) {
  33142. this.indices = [];
  33143. }
  33144. var offset = this.positions ? this.positions.length / 3 : 0;
  33145. for (var index = 0; index < other.indices.length; index++) {
  33146. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33147. this.indices.push(other.indices[index] + offset);
  33148. }
  33149. }
  33150. this.positions = this._mergeElement(this.positions, other.positions);
  33151. this.normals = this._mergeElement(this.normals, other.normals);
  33152. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33153. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33154. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33155. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33156. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33157. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33158. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33159. this.colors = this._mergeElement(this.colors, other.colors);
  33160. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33161. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33162. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33163. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33164. return this;
  33165. };
  33166. VertexData.prototype._mergeElement = function (source, other) {
  33167. if (!source) {
  33168. return other;
  33169. }
  33170. if (!other) {
  33171. return source;
  33172. }
  33173. var len = other.length + source.length;
  33174. var isSrcTypedArray = source instanceof Float32Array;
  33175. var isOthTypedArray = other instanceof Float32Array;
  33176. // use non-loop method when the source is Float32Array
  33177. if (isSrcTypedArray) {
  33178. var ret32 = new Float32Array(len);
  33179. ret32.set(source);
  33180. ret32.set(other, source.length);
  33181. return ret32;
  33182. // source is number[], when other is also use concat
  33183. }
  33184. else if (!isOthTypedArray) {
  33185. return source.concat(other);
  33186. // source is a number[], but other is a Float32Array, loop required
  33187. }
  33188. else {
  33189. var ret = source.slice(0); // copy source to a separate array
  33190. for (var i = 0, len = other.length; i < len; i++) {
  33191. ret.push(other[i]);
  33192. }
  33193. return ret;
  33194. }
  33195. };
  33196. VertexData.prototype._validate = function () {
  33197. if (!this.positions) {
  33198. throw new Error("Positions are required");
  33199. }
  33200. var getElementCount = function (kind, values) {
  33201. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33202. if ((values.length % stride) !== 0) {
  33203. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33204. }
  33205. return values.length / stride;
  33206. };
  33207. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33208. var validateElementCount = function (kind, values) {
  33209. var elementCount = getElementCount(kind, values);
  33210. if (elementCount !== positionsElementCount) {
  33211. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33212. }
  33213. };
  33214. if (this.normals)
  33215. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33216. if (this.tangents)
  33217. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33218. if (this.uvs)
  33219. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33220. if (this.uvs2)
  33221. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33222. if (this.uvs3)
  33223. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33224. if (this.uvs4)
  33225. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33226. if (this.uvs5)
  33227. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33228. if (this.uvs6)
  33229. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33230. if (this.colors)
  33231. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33232. if (this.matricesIndices)
  33233. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33234. if (this.matricesWeights)
  33235. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33236. if (this.matricesIndicesExtra)
  33237. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33238. if (this.matricesWeightsExtra)
  33239. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33240. };
  33241. /**
  33242. * Serializes the VertexData.
  33243. * Returns a serialized object.
  33244. */
  33245. VertexData.prototype.serialize = function () {
  33246. var serializationObject = this.serialize();
  33247. if (this.positions) {
  33248. serializationObject.positions = this.positions;
  33249. }
  33250. if (this.normals) {
  33251. serializationObject.normals = this.normals;
  33252. }
  33253. if (this.tangents) {
  33254. serializationObject.tangents = this.tangents;
  33255. }
  33256. if (this.uvs) {
  33257. serializationObject.uvs = this.uvs;
  33258. }
  33259. if (this.uvs2) {
  33260. serializationObject.uvs2 = this.uvs2;
  33261. }
  33262. if (this.uvs3) {
  33263. serializationObject.uvs3 = this.uvs3;
  33264. }
  33265. if (this.uvs4) {
  33266. serializationObject.uvs4 = this.uvs4;
  33267. }
  33268. if (this.uvs5) {
  33269. serializationObject.uvs5 = this.uvs5;
  33270. }
  33271. if (this.uvs6) {
  33272. serializationObject.uvs6 = this.uvs6;
  33273. }
  33274. if (this.colors) {
  33275. serializationObject.colors = this.colors;
  33276. }
  33277. if (this.matricesIndices) {
  33278. serializationObject.matricesIndices = this.matricesIndices;
  33279. serializationObject.matricesIndices._isExpanded = true;
  33280. }
  33281. if (this.matricesWeights) {
  33282. serializationObject.matricesWeights = this.matricesWeights;
  33283. }
  33284. if (this.matricesIndicesExtra) {
  33285. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33286. serializationObject.matricesIndicesExtra._isExpanded = true;
  33287. }
  33288. if (this.matricesWeightsExtra) {
  33289. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33290. }
  33291. serializationObject.indices = this.indices;
  33292. return serializationObject;
  33293. };
  33294. // Statics
  33295. /**
  33296. * Returns the object VertexData associated to the passed mesh.
  33297. */
  33298. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33299. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33300. };
  33301. /**
  33302. * Returns the object VertexData associated to the passed geometry.
  33303. */
  33304. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33305. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33306. };
  33307. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33308. var result = new VertexData();
  33309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33310. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33311. }
  33312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33313. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33314. }
  33315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33316. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33317. }
  33318. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33319. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33320. }
  33321. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33322. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33323. }
  33324. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33325. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33326. }
  33327. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33328. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33329. }
  33330. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33331. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33332. }
  33333. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33334. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33335. }
  33336. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33337. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33338. }
  33339. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33340. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33341. }
  33342. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33343. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33344. }
  33345. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33346. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33347. }
  33348. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33349. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33350. }
  33351. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33352. return result;
  33353. };
  33354. /**
  33355. * Creates the vertexData of the Ribbon.
  33356. */
  33357. VertexData.CreateRibbon = function (options) {
  33358. var pathArray = options.pathArray;
  33359. var closeArray = options.closeArray || false;
  33360. var closePath = options.closePath || false;
  33361. var invertUV = options.invertUV || false;
  33362. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33363. var offset = options.offset || defaultOffset;
  33364. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33365. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33366. var customUV = options.uvs;
  33367. var customColors = options.colors;
  33368. var positions = [];
  33369. var indices = [];
  33370. var normals = [];
  33371. var uvs = [];
  33372. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33373. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33374. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33375. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33376. var minlg; // minimal length among all paths from pathArray
  33377. var lg = []; // array of path lengths : nb of vertex per path
  33378. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33379. var p; // path iterator
  33380. var i; // point iterator
  33381. var j; // point iterator
  33382. // if single path in pathArray
  33383. if (pathArray.length < 2) {
  33384. var ar1 = [];
  33385. var ar2 = [];
  33386. for (i = 0; i < pathArray[0].length - offset; i++) {
  33387. ar1.push(pathArray[0][i]);
  33388. ar2.push(pathArray[0][i + offset]);
  33389. }
  33390. pathArray = [ar1, ar2];
  33391. }
  33392. // positions and horizontal distances (u)
  33393. var idc = 0;
  33394. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33395. var path;
  33396. var l;
  33397. minlg = pathArray[0].length;
  33398. var vectlg;
  33399. var dist;
  33400. for (p = 0; p < pathArray.length; p++) {
  33401. uTotalDistance[p] = 0;
  33402. us[p] = [0];
  33403. path = pathArray[p];
  33404. l = path.length;
  33405. minlg = (minlg < l) ? minlg : l;
  33406. j = 0;
  33407. while (j < l) {
  33408. positions.push(path[j].x, path[j].y, path[j].z);
  33409. if (j > 0) {
  33410. vectlg = path[j].subtract(path[j - 1]).length();
  33411. dist = vectlg + uTotalDistance[p];
  33412. us[p].push(dist);
  33413. uTotalDistance[p] = dist;
  33414. }
  33415. j++;
  33416. }
  33417. if (closePath) {
  33418. j--;
  33419. positions.push(path[0].x, path[0].y, path[0].z);
  33420. vectlg = path[j].subtract(path[0]).length();
  33421. dist = vectlg + uTotalDistance[p];
  33422. us[p].push(dist);
  33423. uTotalDistance[p] = dist;
  33424. }
  33425. lg[p] = l + closePathCorr;
  33426. idx[p] = idc;
  33427. idc += (l + closePathCorr);
  33428. }
  33429. // vertical distances (v)
  33430. var path1;
  33431. var path2;
  33432. var vertex1 = null;
  33433. var vertex2 = null;
  33434. for (i = 0; i < minlg + closePathCorr; i++) {
  33435. vTotalDistance[i] = 0;
  33436. vs[i] = [0];
  33437. for (p = 0; p < pathArray.length - 1; p++) {
  33438. path1 = pathArray[p];
  33439. path2 = pathArray[p + 1];
  33440. if (i === minlg) {
  33441. vertex1 = path1[0];
  33442. vertex2 = path2[0];
  33443. }
  33444. else {
  33445. vertex1 = path1[i];
  33446. vertex2 = path2[i];
  33447. }
  33448. vectlg = vertex2.subtract(vertex1).length();
  33449. dist = vectlg + vTotalDistance[i];
  33450. vs[i].push(dist);
  33451. vTotalDistance[i] = dist;
  33452. }
  33453. if (closeArray && vertex2 && vertex1) {
  33454. path1 = pathArray[p];
  33455. path2 = pathArray[0];
  33456. if (i === minlg) {
  33457. vertex2 = path2[0];
  33458. }
  33459. vectlg = vertex2.subtract(vertex1).length();
  33460. dist = vectlg + vTotalDistance[i];
  33461. vTotalDistance[i] = dist;
  33462. }
  33463. }
  33464. // uvs
  33465. var u;
  33466. var v;
  33467. if (customUV) {
  33468. for (p = 0; p < customUV.length; p++) {
  33469. uvs.push(customUV[p].x, customUV[p].y);
  33470. }
  33471. }
  33472. else {
  33473. for (p = 0; p < pathArray.length; p++) {
  33474. for (i = 0; i < minlg + closePathCorr; i++) {
  33475. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33476. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33477. if (invertUV) {
  33478. uvs.push(v, u);
  33479. }
  33480. else {
  33481. uvs.push(u, v);
  33482. }
  33483. }
  33484. }
  33485. }
  33486. // indices
  33487. p = 0; // path index
  33488. var pi = 0; // positions array index
  33489. var l1 = lg[p] - 1; // path1 length
  33490. var l2 = lg[p + 1] - 1; // path2 length
  33491. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33492. var shft = idx[1] - idx[0]; // shift
  33493. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33494. while (pi <= min && p < path1nb) {
  33495. // 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
  33496. indices.push(pi, pi + shft, pi + 1);
  33497. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33498. pi += 1;
  33499. if (pi === min) {
  33500. p++;
  33501. if (p === lg.length - 1) {
  33502. shft = idx[0] - idx[p];
  33503. l1 = lg[p] - 1;
  33504. l2 = lg[0] - 1;
  33505. }
  33506. else {
  33507. shft = idx[p + 1] - idx[p];
  33508. l1 = lg[p] - 1;
  33509. l2 = lg[p + 1] - 1;
  33510. }
  33511. pi = idx[p];
  33512. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33513. }
  33514. }
  33515. // normals
  33516. VertexData.ComputeNormals(positions, indices, normals);
  33517. if (closePath) {
  33518. var indexFirst = 0;
  33519. var indexLast = 0;
  33520. for (p = 0; p < pathArray.length; p++) {
  33521. indexFirst = idx[p] * 3;
  33522. if (p + 1 < pathArray.length) {
  33523. indexLast = (idx[p + 1] - 1) * 3;
  33524. }
  33525. else {
  33526. indexLast = normals.length - 3;
  33527. }
  33528. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33529. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33530. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33531. normals[indexLast] = normals[indexFirst];
  33532. normals[indexLast + 1] = normals[indexFirst + 1];
  33533. normals[indexLast + 2] = normals[indexFirst + 2];
  33534. }
  33535. }
  33536. // sides
  33537. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33538. // Colors
  33539. var colors = null;
  33540. if (customColors) {
  33541. colors = new Float32Array(customColors.length * 4);
  33542. for (var c = 0; c < customColors.length; c++) {
  33543. colors[c * 4] = customColors[c].r;
  33544. colors[c * 4 + 1] = customColors[c].g;
  33545. colors[c * 4 + 2] = customColors[c].b;
  33546. colors[c * 4 + 3] = customColors[c].a;
  33547. }
  33548. }
  33549. // Result
  33550. var vertexData = new VertexData();
  33551. var positions32 = new Float32Array(positions);
  33552. var normals32 = new Float32Array(normals);
  33553. var uvs32 = new Float32Array(uvs);
  33554. vertexData.indices = indices;
  33555. vertexData.positions = positions32;
  33556. vertexData.normals = normals32;
  33557. vertexData.uvs = uvs32;
  33558. if (colors) {
  33559. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33560. }
  33561. if (closePath) {
  33562. vertexData._idx = idx;
  33563. }
  33564. return vertexData;
  33565. };
  33566. /**
  33567. * Creates the VertexData of the Box.
  33568. */
  33569. VertexData.CreateBox = function (options) {
  33570. var normalsSource = [
  33571. new BABYLON.Vector3(0, 0, 1),
  33572. new BABYLON.Vector3(0, 0, -1),
  33573. new BABYLON.Vector3(1, 0, 0),
  33574. new BABYLON.Vector3(-1, 0, 0),
  33575. new BABYLON.Vector3(0, 1, 0),
  33576. new BABYLON.Vector3(0, -1, 0)
  33577. ];
  33578. var indices = [];
  33579. var positions = [];
  33580. var normals = [];
  33581. var uvs = [];
  33582. var width = options.width || options.size || 1;
  33583. var height = options.height || options.size || 1;
  33584. var depth = options.depth || options.size || 1;
  33585. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33586. var faceUV = options.faceUV || new Array(6);
  33587. var faceColors = options.faceColors;
  33588. var colors = [];
  33589. // default face colors and UV if undefined
  33590. for (var f = 0; f < 6; f++) {
  33591. if (faceUV[f] === undefined) {
  33592. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33593. }
  33594. if (faceColors && faceColors[f] === undefined) {
  33595. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33596. }
  33597. }
  33598. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33599. // Create each face in turn.
  33600. for (var index = 0; index < normalsSource.length; index++) {
  33601. var normal = normalsSource[index];
  33602. // Get two vectors perpendicular to the face normal and to each other.
  33603. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33604. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33605. // Six indices (two triangles) per face.
  33606. var verticesLength = positions.length / 3;
  33607. indices.push(verticesLength);
  33608. indices.push(verticesLength + 1);
  33609. indices.push(verticesLength + 2);
  33610. indices.push(verticesLength);
  33611. indices.push(verticesLength + 2);
  33612. indices.push(verticesLength + 3);
  33613. // Four vertices per face.
  33614. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33615. positions.push(vertex.x, vertex.y, vertex.z);
  33616. normals.push(normal.x, normal.y, normal.z);
  33617. uvs.push(faceUV[index].z, faceUV[index].w);
  33618. if (faceColors) {
  33619. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33620. }
  33621. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33622. positions.push(vertex.x, vertex.y, vertex.z);
  33623. normals.push(normal.x, normal.y, normal.z);
  33624. uvs.push(faceUV[index].x, faceUV[index].w);
  33625. if (faceColors) {
  33626. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33627. }
  33628. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33629. positions.push(vertex.x, vertex.y, vertex.z);
  33630. normals.push(normal.x, normal.y, normal.z);
  33631. uvs.push(faceUV[index].x, faceUV[index].y);
  33632. if (faceColors) {
  33633. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33634. }
  33635. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33636. positions.push(vertex.x, vertex.y, vertex.z);
  33637. normals.push(normal.x, normal.y, normal.z);
  33638. uvs.push(faceUV[index].z, faceUV[index].y);
  33639. if (faceColors) {
  33640. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33641. }
  33642. }
  33643. // sides
  33644. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33645. // Result
  33646. var vertexData = new VertexData();
  33647. vertexData.indices = indices;
  33648. vertexData.positions = positions;
  33649. vertexData.normals = normals;
  33650. vertexData.uvs = uvs;
  33651. if (faceColors) {
  33652. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33653. vertexData.colors = totalColors;
  33654. }
  33655. return vertexData;
  33656. };
  33657. /**
  33658. * Creates the VertexData of the Sphere.
  33659. */
  33660. VertexData.CreateSphere = function (options) {
  33661. var segments = options.segments || 32;
  33662. var diameterX = options.diameterX || options.diameter || 1;
  33663. var diameterY = options.diameterY || options.diameter || 1;
  33664. var diameterZ = options.diameterZ || options.diameter || 1;
  33665. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33666. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33667. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33668. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33669. var totalZRotationSteps = 2 + segments;
  33670. var totalYRotationSteps = 2 * totalZRotationSteps;
  33671. var indices = [];
  33672. var positions = [];
  33673. var normals = [];
  33674. var uvs = [];
  33675. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33676. var normalizedZ = zRotationStep / totalZRotationSteps;
  33677. var angleZ = normalizedZ * Math.PI * slice;
  33678. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33679. var normalizedY = yRotationStep / totalYRotationSteps;
  33680. var angleY = normalizedY * Math.PI * 2 * arc;
  33681. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33682. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33683. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33684. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33685. var vertex = complete.multiply(radius);
  33686. var normal = complete.divide(radius).normalize();
  33687. positions.push(vertex.x, vertex.y, vertex.z);
  33688. normals.push(normal.x, normal.y, normal.z);
  33689. uvs.push(normalizedY, normalizedZ);
  33690. }
  33691. if (zRotationStep > 0) {
  33692. var verticesCount = positions.length / 3;
  33693. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33694. indices.push((firstIndex));
  33695. indices.push((firstIndex + 1));
  33696. indices.push(firstIndex + totalYRotationSteps + 1);
  33697. indices.push((firstIndex + totalYRotationSteps + 1));
  33698. indices.push((firstIndex + 1));
  33699. indices.push((firstIndex + totalYRotationSteps + 2));
  33700. }
  33701. }
  33702. }
  33703. // Sides
  33704. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33705. // Result
  33706. var vertexData = new VertexData();
  33707. vertexData.indices = indices;
  33708. vertexData.positions = positions;
  33709. vertexData.normals = normals;
  33710. vertexData.uvs = uvs;
  33711. return vertexData;
  33712. };
  33713. /**
  33714. * Creates the VertexData of the Cylinder or Cone.
  33715. */
  33716. VertexData.CreateCylinder = function (options) {
  33717. var height = options.height || 2;
  33718. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33719. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33720. var tessellation = options.tessellation || 24;
  33721. var subdivisions = options.subdivisions || 1;
  33722. var hasRings = options.hasRings ? true : false;
  33723. var enclose = options.enclose ? true : false;
  33724. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33725. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33726. var faceUV = options.faceUV || new Array(3);
  33727. var faceColors = options.faceColors;
  33728. // default face colors and UV if undefined
  33729. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33730. var ringNb = (hasRings) ? subdivisions : 1;
  33731. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33732. var f;
  33733. for (f = 0; f < surfaceNb; f++) {
  33734. if (faceColors && faceColors[f] === undefined) {
  33735. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33736. }
  33737. }
  33738. for (f = 0; f < surfaceNb; f++) {
  33739. if (faceUV && faceUV[f] === undefined) {
  33740. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33741. }
  33742. }
  33743. var indices = new Array();
  33744. var positions = new Array();
  33745. var normals = new Array();
  33746. var uvs = new Array();
  33747. var colors = new Array();
  33748. var angle_step = Math.PI * 2 * arc / tessellation;
  33749. var angle;
  33750. var h;
  33751. var radius;
  33752. var tan = (diameterBottom - diameterTop) / 2 / height;
  33753. var ringVertex = BABYLON.Vector3.Zero();
  33754. var ringNormal = BABYLON.Vector3.Zero();
  33755. var ringFirstVertex = BABYLON.Vector3.Zero();
  33756. var ringFirstNormal = BABYLON.Vector3.Zero();
  33757. var quadNormal = BABYLON.Vector3.Zero();
  33758. var Y = BABYLON.Axis.Y;
  33759. // positions, normals, uvs
  33760. var i;
  33761. var j;
  33762. var r;
  33763. var ringIdx = 1;
  33764. var s = 1; // surface index
  33765. var cs = 0;
  33766. var v = 0;
  33767. for (i = 0; i <= subdivisions; i++) {
  33768. h = i / subdivisions;
  33769. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33770. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33771. for (r = 0; r < ringIdx; r++) {
  33772. if (hasRings) {
  33773. s += r;
  33774. }
  33775. if (enclose) {
  33776. s += 2 * r;
  33777. }
  33778. for (j = 0; j <= tessellation; j++) {
  33779. angle = j * angle_step;
  33780. // position
  33781. ringVertex.x = Math.cos(-angle) * radius;
  33782. ringVertex.y = -height / 2 + h * height;
  33783. ringVertex.z = Math.sin(-angle) * radius;
  33784. // normal
  33785. if (diameterTop === 0 && i === subdivisions) {
  33786. // if no top cap, reuse former normals
  33787. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33788. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33789. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33790. }
  33791. else {
  33792. ringNormal.x = ringVertex.x;
  33793. ringNormal.z = ringVertex.z;
  33794. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33795. ringNormal.normalize();
  33796. }
  33797. // keep first ring vertex values for enclose
  33798. if (j === 0) {
  33799. ringFirstVertex.copyFrom(ringVertex);
  33800. ringFirstNormal.copyFrom(ringNormal);
  33801. }
  33802. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33803. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33804. if (hasRings) {
  33805. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33806. }
  33807. else {
  33808. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33809. }
  33810. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33811. if (faceColors) {
  33812. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33813. }
  33814. }
  33815. // if enclose, add four vertices and their dedicated normals
  33816. if (arc !== 1 && enclose) {
  33817. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33818. positions.push(0, ringVertex.y, 0);
  33819. positions.push(0, ringVertex.y, 0);
  33820. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33821. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33822. quadNormal.normalize();
  33823. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33824. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33825. quadNormal.normalize();
  33826. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33827. if (hasRings) {
  33828. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33829. }
  33830. else {
  33831. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33832. }
  33833. uvs.push(faceUV[s + 1].x, v);
  33834. uvs.push(faceUV[s + 1].z, v);
  33835. if (hasRings) {
  33836. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33837. }
  33838. else {
  33839. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33840. }
  33841. uvs.push(faceUV[s + 2].x, v);
  33842. uvs.push(faceUV[s + 2].z, v);
  33843. if (faceColors) {
  33844. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33845. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33846. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33847. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33848. }
  33849. }
  33850. if (cs !== s) {
  33851. cs = s;
  33852. }
  33853. }
  33854. }
  33855. // indices
  33856. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33857. var s;
  33858. i = 0;
  33859. for (s = 0; s < subdivisions; s++) {
  33860. var i0 = 0;
  33861. var i1 = 0;
  33862. var i2 = 0;
  33863. var i3 = 0;
  33864. for (j = 0; j < tessellation; j++) {
  33865. i0 = i * (e + 1) + j;
  33866. i1 = (i + 1) * (e + 1) + j;
  33867. i2 = i * (e + 1) + (j + 1);
  33868. i3 = (i + 1) * (e + 1) + (j + 1);
  33869. indices.push(i0, i1, i2);
  33870. indices.push(i3, i2, i1);
  33871. }
  33872. if (arc !== 1 && enclose) {
  33873. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33874. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33875. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33876. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33877. }
  33878. i = (hasRings) ? (i + 2) : (i + 1);
  33879. }
  33880. // Caps
  33881. var createCylinderCap = function (isTop) {
  33882. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33883. if (radius === 0) {
  33884. return;
  33885. }
  33886. // Cap positions, normals & uvs
  33887. var angle;
  33888. var circleVector;
  33889. var i;
  33890. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33891. var c = null;
  33892. if (faceColors) {
  33893. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33894. }
  33895. // cap center
  33896. var vbase = positions.length / 3;
  33897. var offset = isTop ? height / 2 : -height / 2;
  33898. var center = new BABYLON.Vector3(0, offset, 0);
  33899. positions.push(center.x, center.y, center.z);
  33900. normals.push(0, isTop ? 1 : -1, 0);
  33901. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33902. if (c) {
  33903. colors.push(c.r, c.g, c.b, c.a);
  33904. }
  33905. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33906. for (i = 0; i <= tessellation; i++) {
  33907. angle = Math.PI * 2 * i * arc / tessellation;
  33908. var cos = Math.cos(-angle);
  33909. var sin = Math.sin(-angle);
  33910. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33911. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33912. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33913. normals.push(0, isTop ? 1 : -1, 0);
  33914. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33915. if (c) {
  33916. colors.push(c.r, c.g, c.b, c.a);
  33917. }
  33918. }
  33919. // Cap indices
  33920. for (i = 0; i < tessellation; i++) {
  33921. if (!isTop) {
  33922. indices.push(vbase);
  33923. indices.push(vbase + (i + 1));
  33924. indices.push(vbase + (i + 2));
  33925. }
  33926. else {
  33927. indices.push(vbase);
  33928. indices.push(vbase + (i + 2));
  33929. indices.push(vbase + (i + 1));
  33930. }
  33931. }
  33932. };
  33933. // add caps to geometry
  33934. createCylinderCap(false);
  33935. createCylinderCap(true);
  33936. // Sides
  33937. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33938. var vertexData = new VertexData();
  33939. vertexData.indices = indices;
  33940. vertexData.positions = positions;
  33941. vertexData.normals = normals;
  33942. vertexData.uvs = uvs;
  33943. if (faceColors) {
  33944. vertexData.colors = colors;
  33945. }
  33946. return vertexData;
  33947. };
  33948. /**
  33949. * Creates the VertexData of the Torus.
  33950. */
  33951. VertexData.CreateTorus = function (options) {
  33952. var indices = [];
  33953. var positions = [];
  33954. var normals = [];
  33955. var uvs = [];
  33956. var diameter = options.diameter || 1;
  33957. var thickness = options.thickness || 0.5;
  33958. var tessellation = options.tessellation || 16;
  33959. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33960. var stride = tessellation + 1;
  33961. for (var i = 0; i <= tessellation; i++) {
  33962. var u = i / tessellation;
  33963. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33964. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33965. for (var j = 0; j <= tessellation; j++) {
  33966. var v = 1 - j / tessellation;
  33967. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33968. var dx = Math.cos(innerAngle);
  33969. var dy = Math.sin(innerAngle);
  33970. // Create a vertex.
  33971. var normal = new BABYLON.Vector3(dx, dy, 0);
  33972. var position = normal.scale(thickness / 2);
  33973. var textureCoordinate = new BABYLON.Vector2(u, v);
  33974. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33975. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33976. positions.push(position.x, position.y, position.z);
  33977. normals.push(normal.x, normal.y, normal.z);
  33978. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33979. // And create indices for two triangles.
  33980. var nextI = (i + 1) % stride;
  33981. var nextJ = (j + 1) % stride;
  33982. indices.push(i * stride + j);
  33983. indices.push(i * stride + nextJ);
  33984. indices.push(nextI * stride + j);
  33985. indices.push(i * stride + nextJ);
  33986. indices.push(nextI * stride + nextJ);
  33987. indices.push(nextI * stride + j);
  33988. }
  33989. }
  33990. // Sides
  33991. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33992. // Result
  33993. var vertexData = new VertexData();
  33994. vertexData.indices = indices;
  33995. vertexData.positions = positions;
  33996. vertexData.normals = normals;
  33997. vertexData.uvs = uvs;
  33998. return vertexData;
  33999. };
  34000. /**
  34001. * Creates the VertexData of the LineSystem.
  34002. */
  34003. VertexData.CreateLineSystem = function (options) {
  34004. var indices = [];
  34005. var positions = [];
  34006. var lines = options.lines;
  34007. var colors = options.colors;
  34008. var vertexColors = [];
  34009. var idx = 0;
  34010. for (var l = 0; l < lines.length; l++) {
  34011. var points = lines[l];
  34012. for (var index = 0; index < points.length; index++) {
  34013. positions.push(points[index].x, points[index].y, points[index].z);
  34014. if (colors) {
  34015. var color = colors[l];
  34016. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  34017. }
  34018. if (index > 0) {
  34019. indices.push(idx - 1);
  34020. indices.push(idx);
  34021. }
  34022. idx++;
  34023. }
  34024. }
  34025. var vertexData = new VertexData();
  34026. vertexData.indices = indices;
  34027. vertexData.positions = positions;
  34028. if (colors) {
  34029. vertexData.colors = vertexColors;
  34030. }
  34031. return vertexData;
  34032. };
  34033. /**
  34034. * Create the VertexData of the DashedLines.
  34035. */
  34036. VertexData.CreateDashedLines = function (options) {
  34037. var dashSize = options.dashSize || 3;
  34038. var gapSize = options.gapSize || 1;
  34039. var dashNb = options.dashNb || 200;
  34040. var points = options.points;
  34041. var positions = new Array();
  34042. var indices = new Array();
  34043. var curvect = BABYLON.Vector3.Zero();
  34044. var lg = 0;
  34045. var nb = 0;
  34046. var shft = 0;
  34047. var dashshft = 0;
  34048. var curshft = 0;
  34049. var idx = 0;
  34050. var i = 0;
  34051. for (i = 0; i < points.length - 1; i++) {
  34052. points[i + 1].subtractToRef(points[i], curvect);
  34053. lg += curvect.length();
  34054. }
  34055. shft = lg / dashNb;
  34056. dashshft = dashSize * shft / (dashSize + gapSize);
  34057. for (i = 0; i < points.length - 1; i++) {
  34058. points[i + 1].subtractToRef(points[i], curvect);
  34059. nb = Math.floor(curvect.length() / shft);
  34060. curvect.normalize();
  34061. for (var j = 0; j < nb; j++) {
  34062. curshft = shft * j;
  34063. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34064. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34065. indices.push(idx, idx + 1);
  34066. idx += 2;
  34067. }
  34068. }
  34069. // Result
  34070. var vertexData = new VertexData();
  34071. vertexData.positions = positions;
  34072. vertexData.indices = indices;
  34073. return vertexData;
  34074. };
  34075. /**
  34076. * Creates the VertexData of the Ground.
  34077. */
  34078. VertexData.CreateGround = function (options) {
  34079. var indices = [];
  34080. var positions = [];
  34081. var normals = [];
  34082. var uvs = [];
  34083. var row, col;
  34084. var width = options.width || 1;
  34085. var height = options.height || 1;
  34086. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34087. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34088. for (row = 0; row <= subdivisionsY; row++) {
  34089. for (col = 0; col <= subdivisionsX; col++) {
  34090. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34091. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34092. positions.push(position.x, position.y, position.z);
  34093. normals.push(normal.x, normal.y, normal.z);
  34094. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34095. }
  34096. }
  34097. for (row = 0; row < subdivisionsY; row++) {
  34098. for (col = 0; col < subdivisionsX; col++) {
  34099. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34100. indices.push(col + 1 + row * (subdivisionsX + 1));
  34101. indices.push(col + row * (subdivisionsX + 1));
  34102. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34103. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34104. indices.push(col + row * (subdivisionsX + 1));
  34105. }
  34106. }
  34107. // Result
  34108. var vertexData = new VertexData();
  34109. vertexData.indices = indices;
  34110. vertexData.positions = positions;
  34111. vertexData.normals = normals;
  34112. vertexData.uvs = uvs;
  34113. return vertexData;
  34114. };
  34115. /**
  34116. * Creates the VertexData of the TiledGround.
  34117. */
  34118. VertexData.CreateTiledGround = function (options) {
  34119. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34120. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34121. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34122. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34123. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34124. var precision = options.precision || { w: 1, h: 1 };
  34125. var indices = new Array();
  34126. var positions = new Array();
  34127. var normals = new Array();
  34128. var uvs = new Array();
  34129. var row, col, tileRow, tileCol;
  34130. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34131. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34132. precision.w = (precision.w < 1) ? 1 : precision.w;
  34133. precision.h = (precision.h < 1) ? 1 : precision.h;
  34134. var tileSize = {
  34135. 'w': (xmax - xmin) / subdivisions.w,
  34136. 'h': (zmax - zmin) / subdivisions.h
  34137. };
  34138. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34139. // Indices
  34140. var base = positions.length / 3;
  34141. var rowLength = precision.w + 1;
  34142. for (row = 0; row < precision.h; row++) {
  34143. for (col = 0; col < precision.w; col++) {
  34144. var square = [
  34145. base + col + row * rowLength,
  34146. base + (col + 1) + row * rowLength,
  34147. base + (col + 1) + (row + 1) * rowLength,
  34148. base + col + (row + 1) * rowLength
  34149. ];
  34150. indices.push(square[1]);
  34151. indices.push(square[2]);
  34152. indices.push(square[3]);
  34153. indices.push(square[0]);
  34154. indices.push(square[1]);
  34155. indices.push(square[3]);
  34156. }
  34157. }
  34158. // Position, normals and uvs
  34159. var position = BABYLON.Vector3.Zero();
  34160. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34161. for (row = 0; row <= precision.h; row++) {
  34162. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34163. for (col = 0; col <= precision.w; col++) {
  34164. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34165. position.y = 0;
  34166. positions.push(position.x, position.y, position.z);
  34167. normals.push(normal.x, normal.y, normal.z);
  34168. uvs.push(col / precision.w, row / precision.h);
  34169. }
  34170. }
  34171. }
  34172. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34173. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34174. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34175. }
  34176. }
  34177. // Result
  34178. var vertexData = new VertexData();
  34179. vertexData.indices = indices;
  34180. vertexData.positions = positions;
  34181. vertexData.normals = normals;
  34182. vertexData.uvs = uvs;
  34183. return vertexData;
  34184. };
  34185. /**
  34186. * Creates the VertexData of the Ground designed from a heightmap.
  34187. */
  34188. VertexData.CreateGroundFromHeightMap = function (options) {
  34189. var indices = [];
  34190. var positions = [];
  34191. var normals = [];
  34192. var uvs = [];
  34193. var row, col;
  34194. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34195. // Vertices
  34196. for (row = 0; row <= options.subdivisions; row++) {
  34197. for (col = 0; col <= options.subdivisions; col++) {
  34198. 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));
  34199. // Compute height
  34200. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34201. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34202. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34203. var r = options.buffer[pos] / 255.0;
  34204. var g = options.buffer[pos + 1] / 255.0;
  34205. var b = options.buffer[pos + 2] / 255.0;
  34206. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34207. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34208. // Add vertex
  34209. positions.push(position.x, position.y, position.z);
  34210. normals.push(0, 0, 0);
  34211. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34212. }
  34213. }
  34214. // Indices
  34215. for (row = 0; row < options.subdivisions; row++) {
  34216. for (col = 0; col < options.subdivisions; col++) {
  34217. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34218. indices.push(col + 1 + row * (options.subdivisions + 1));
  34219. indices.push(col + row * (options.subdivisions + 1));
  34220. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34221. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34222. indices.push(col + row * (options.subdivisions + 1));
  34223. }
  34224. }
  34225. // Normals
  34226. VertexData.ComputeNormals(positions, indices, normals);
  34227. // Result
  34228. var vertexData = new VertexData();
  34229. vertexData.indices = indices;
  34230. vertexData.positions = positions;
  34231. vertexData.normals = normals;
  34232. vertexData.uvs = uvs;
  34233. return vertexData;
  34234. };
  34235. /**
  34236. * Creates the VertexData of the Plane.
  34237. */
  34238. VertexData.CreatePlane = function (options) {
  34239. var indices = [];
  34240. var positions = [];
  34241. var normals = [];
  34242. var uvs = [];
  34243. var width = options.width || options.size || 1;
  34244. var height = options.height || options.size || 1;
  34245. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34246. // Vertices
  34247. var halfWidth = width / 2.0;
  34248. var halfHeight = height / 2.0;
  34249. positions.push(-halfWidth, -halfHeight, 0);
  34250. normals.push(0, 0, -1.0);
  34251. uvs.push(0.0, 0.0);
  34252. positions.push(halfWidth, -halfHeight, 0);
  34253. normals.push(0, 0, -1.0);
  34254. uvs.push(1.0, 0.0);
  34255. positions.push(halfWidth, halfHeight, 0);
  34256. normals.push(0, 0, -1.0);
  34257. uvs.push(1.0, 1.0);
  34258. positions.push(-halfWidth, halfHeight, 0);
  34259. normals.push(0, 0, -1.0);
  34260. uvs.push(0.0, 1.0);
  34261. // Indices
  34262. indices.push(0);
  34263. indices.push(1);
  34264. indices.push(2);
  34265. indices.push(0);
  34266. indices.push(2);
  34267. indices.push(3);
  34268. // Sides
  34269. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34270. // Result
  34271. var vertexData = new VertexData();
  34272. vertexData.indices = indices;
  34273. vertexData.positions = positions;
  34274. vertexData.normals = normals;
  34275. vertexData.uvs = uvs;
  34276. return vertexData;
  34277. };
  34278. /**
  34279. * Creates the VertexData of the Disc or regular Polygon.
  34280. */
  34281. VertexData.CreateDisc = function (options) {
  34282. var positions = new Array();
  34283. var indices = new Array();
  34284. var normals = new Array();
  34285. var uvs = new Array();
  34286. var radius = options.radius || 0.5;
  34287. var tessellation = options.tessellation || 64;
  34288. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34289. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34290. // positions and uvs
  34291. positions.push(0, 0, 0); // disc center first
  34292. uvs.push(0.5, 0.5);
  34293. var theta = Math.PI * 2 * arc;
  34294. var step = theta / tessellation;
  34295. for (var a = 0; a < theta; a += step) {
  34296. var x = Math.cos(a);
  34297. var y = Math.sin(a);
  34298. var u = (x + 1) / 2;
  34299. var v = (1 - y) / 2;
  34300. positions.push(radius * x, radius * y, 0);
  34301. uvs.push(u, v);
  34302. }
  34303. if (arc === 1) {
  34304. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34305. uvs.push(uvs[2], uvs[3]);
  34306. }
  34307. //indices
  34308. var vertexNb = positions.length / 3;
  34309. for (var i = 1; i < vertexNb - 1; i++) {
  34310. indices.push(i + 1, 0, i);
  34311. }
  34312. // result
  34313. VertexData.ComputeNormals(positions, indices, normals);
  34314. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34315. var vertexData = new VertexData();
  34316. vertexData.indices = indices;
  34317. vertexData.positions = positions;
  34318. vertexData.normals = normals;
  34319. vertexData.uvs = uvs;
  34320. return vertexData;
  34321. };
  34322. /**
  34323. * Re-creates the VertexData of the Polygon for sideOrientation.
  34324. */
  34325. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34326. var faceUV = fUV || new Array(3);
  34327. var faceColors = fColors;
  34328. var colors = [];
  34329. // default face colors and UV if undefined
  34330. for (var f = 0; f < 3; f++) {
  34331. if (faceUV[f] === undefined) {
  34332. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34333. }
  34334. if (faceColors && faceColors[f] === undefined) {
  34335. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34336. }
  34337. }
  34338. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34339. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34340. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34341. var indices = polygon.getIndices();
  34342. // set face colours and textures
  34343. var idx = 0;
  34344. var face = 0;
  34345. for (var index = 0; index < normals.length; index += 3) {
  34346. //Edge Face no. 1
  34347. if (Math.abs(normals[index + 1]) < 0.001) {
  34348. face = 1;
  34349. }
  34350. //Top Face no. 0
  34351. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34352. face = 0;
  34353. }
  34354. //Bottom Face no. 2
  34355. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34356. face = 2;
  34357. }
  34358. idx = index / 3;
  34359. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34360. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34361. if (faceColors) {
  34362. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34363. }
  34364. }
  34365. // sides
  34366. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34367. // Result
  34368. var vertexData = new VertexData();
  34369. vertexData.indices = indices;
  34370. vertexData.positions = positions;
  34371. vertexData.normals = normals;
  34372. vertexData.uvs = uvs;
  34373. if (faceColors) {
  34374. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34375. vertexData.colors = totalColors;
  34376. }
  34377. return vertexData;
  34378. };
  34379. /**
  34380. * Creates the VertexData of the IcoSphere.
  34381. */
  34382. VertexData.CreateIcoSphere = function (options) {
  34383. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34384. var radius = options.radius || 1;
  34385. var flat = (options.flat === undefined) ? true : options.flat;
  34386. var subdivisions = options.subdivisions || 4;
  34387. var radiusX = options.radiusX || radius;
  34388. var radiusY = options.radiusY || radius;
  34389. var radiusZ = options.radiusZ || radius;
  34390. var t = (1 + Math.sqrt(5)) / 2;
  34391. // 12 vertex x,y,z
  34392. var ico_vertices = [
  34393. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34394. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34395. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34396. ];
  34397. // index of 3 vertex makes a face of icopshere
  34398. var ico_indices = [
  34399. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34400. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34401. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34402. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34403. ];
  34404. // vertex for uv have aliased position, not for UV
  34405. var vertices_unalias_id = [
  34406. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34407. // vertex alias
  34408. 0,
  34409. 2,
  34410. 3,
  34411. 3,
  34412. 3,
  34413. 4,
  34414. 7,
  34415. 8,
  34416. 9,
  34417. 9,
  34418. 10,
  34419. 11 // 23: B + 12
  34420. ];
  34421. // uv as integer step (not pixels !)
  34422. var ico_vertexuv = [
  34423. 5, 1, 3, 1, 6, 4, 0, 0,
  34424. 5, 3, 4, 2, 2, 2, 4, 0,
  34425. 2, 0, 1, 1, 6, 0, 6, 2,
  34426. // vertex alias (for same vertex on different faces)
  34427. 0, 4,
  34428. 3, 3,
  34429. 4, 4,
  34430. 3, 1,
  34431. 4, 2,
  34432. 4, 4,
  34433. 0, 2,
  34434. 1, 1,
  34435. 2, 2,
  34436. 3, 3,
  34437. 1, 3,
  34438. 2, 4 // 23: B + 12
  34439. ];
  34440. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34441. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34442. // First island of uv mapping
  34443. // v = 4h 3+ 2
  34444. // v = 3h 9+ 4
  34445. // v = 2h 9+ 5 B
  34446. // v = 1h 9 1 0
  34447. // v = 0h 3 8 7 A
  34448. // u = 0 1 2 3 4 5 6 *a
  34449. // Second island of uv mapping
  34450. // v = 4h 0+ B+ 4+
  34451. // v = 3h A+ 2+
  34452. // v = 2h 7+ 6 3+
  34453. // v = 1h 8+ 3+
  34454. // v = 0h
  34455. // u = 0 1 2 3 4 5 6 *a
  34456. // Face layout on texture UV mapping
  34457. // ============
  34458. // \ 4 /\ 16 / ======
  34459. // \ / \ / /\ 11 /
  34460. // \/ 7 \/ / \ /
  34461. // ======= / 10 \/
  34462. // /\ 17 /\ =======
  34463. // / \ / \ \ 15 /\
  34464. // / 8 \/ 12 \ \ / \
  34465. // ============ \/ 6 \
  34466. // \ 18 /\ ============
  34467. // \ / \ \ 5 /\ 0 /
  34468. // \/ 13 \ \ / \ /
  34469. // ======= \/ 1 \/
  34470. // =============
  34471. // /\ 19 /\ 2 /\
  34472. // / \ / \ / \
  34473. // / 14 \/ 9 \/ 3 \
  34474. // ===================
  34475. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34476. var ustep = 138 / 1024;
  34477. var vstep = 239 / 1024;
  34478. var uoffset = 60 / 1024;
  34479. var voffset = 26 / 1024;
  34480. // Second island should have margin, not to touch the first island
  34481. // avoid any borderline artefact in pixel rounding
  34482. var island_u_offset = -40 / 1024;
  34483. var island_v_offset = +20 / 1024;
  34484. // face is either island 0 or 1 :
  34485. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34486. var island = [
  34487. 0, 0, 0, 0, 1,
  34488. 0, 0, 1, 1, 0,
  34489. 0, 0, 1, 1, 0,
  34490. 0, 1, 1, 1, 0 // 15 - 19
  34491. ];
  34492. var indices = new Array();
  34493. var positions = new Array();
  34494. var normals = new Array();
  34495. var uvs = new Array();
  34496. var current_indice = 0;
  34497. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34498. var face_vertex_pos = new Array(3);
  34499. var face_vertex_uv = new Array(3);
  34500. var v012;
  34501. for (v012 = 0; v012 < 3; v012++) {
  34502. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34503. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34504. }
  34505. // create all with normals
  34506. for (var face = 0; face < 20; face++) {
  34507. // 3 vertex per face
  34508. for (v012 = 0; v012 < 3; v012++) {
  34509. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34510. var v_id = ico_indices[3 * face + v012];
  34511. // vertex have 3D position (x,y,z)
  34512. 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]);
  34513. // Normalize to get normal, then scale to radius
  34514. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34515. // uv Coordinates from vertex ID
  34516. 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);
  34517. }
  34518. // Subdivide the face (interpolate pos, norm, uv)
  34519. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34520. // - norm is linear interpolation of vertex corner normal
  34521. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34522. // - uv is linear interpolation
  34523. //
  34524. // Topology is as below for sub-divide by 2
  34525. // vertex shown as v0,v1,v2
  34526. // interp index is i1 to progress in range [v0,v1[
  34527. // interp index is i2 to progress in range [v0,v2[
  34528. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34529. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34530. //
  34531. //
  34532. // i2 v2
  34533. // ^ ^
  34534. // / / \
  34535. // / / \
  34536. // / / \
  34537. // / / (0,1) \
  34538. // / #---------\
  34539. // / / \ (0,0)'/ \
  34540. // / / \ / \
  34541. // / / \ / \
  34542. // / / (0,0) \ / (1,0) \
  34543. // / #---------#---------\
  34544. // v0 v1
  34545. //
  34546. // --------------------> i1
  34547. //
  34548. // interp of (i1,i2):
  34549. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34550. // along i1 : lerp(x0,x1, i1/(S-i2))
  34551. //
  34552. // centroid of triangle is needed to get help normal computation
  34553. // (c1,c2) are used for centroid location
  34554. var interp_vertex = function (i1, i2, c1, c2) {
  34555. // vertex is interpolated from
  34556. // - face_vertex_pos[0..2]
  34557. // - face_vertex_uv[0..2]
  34558. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34559. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34560. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34561. pos_interp.normalize();
  34562. var vertex_normal;
  34563. if (flat) {
  34564. // in flat mode, recalculate normal as face centroid normal
  34565. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34566. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34567. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34568. }
  34569. else {
  34570. // in smooth mode, recalculate normal from each single vertex position
  34571. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34572. }
  34573. // Vertex normal need correction due to X,Y,Z radius scaling
  34574. vertex_normal.x /= radiusX;
  34575. vertex_normal.y /= radiusY;
  34576. vertex_normal.z /= radiusZ;
  34577. vertex_normal.normalize();
  34578. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34579. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34580. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34581. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34582. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34583. uvs.push(uv_interp.x, uv_interp.y);
  34584. // push each vertex has member of a face
  34585. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34586. indices.push(current_indice);
  34587. current_indice++;
  34588. };
  34589. for (var i2 = 0; i2 < subdivisions; i2++) {
  34590. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34591. // face : (i1,i2) for /\ :
  34592. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34593. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34594. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34595. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34596. if (i1 + i2 + 1 < subdivisions) {
  34597. // face : (i1,i2)' for \/ :
  34598. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34599. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34600. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34601. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34602. }
  34603. }
  34604. }
  34605. }
  34606. // Sides
  34607. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34608. // Result
  34609. var vertexData = new VertexData();
  34610. vertexData.indices = indices;
  34611. vertexData.positions = positions;
  34612. vertexData.normals = normals;
  34613. vertexData.uvs = uvs;
  34614. return vertexData;
  34615. };
  34616. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34617. /**
  34618. * Creates the VertexData of the Polyhedron.
  34619. */
  34620. VertexData.CreatePolyhedron = function (options) {
  34621. // provided polyhedron types :
  34622. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34623. // 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)
  34624. var polyhedra = [];
  34625. 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]] };
  34626. 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]] };
  34627. polyhedra[2] = {
  34628. 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]],
  34629. 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]]
  34630. };
  34631. polyhedra[3] = {
  34632. 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]],
  34633. 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]]
  34634. };
  34635. polyhedra[4] = {
  34636. 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]],
  34637. 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]]
  34638. };
  34639. 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]] };
  34640. 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]] };
  34641. 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]] };
  34642. 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]] };
  34643. 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]] };
  34644. 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]] };
  34645. 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]] };
  34646. 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]] };
  34647. 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]] };
  34648. polyhedra[14] = {
  34649. 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]],
  34650. 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]]
  34651. };
  34652. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34653. var size = options.size;
  34654. var sizeX = options.sizeX || size || 1;
  34655. var sizeY = options.sizeY || size || 1;
  34656. var sizeZ = options.sizeZ || size || 1;
  34657. var data = options.custom || polyhedra[type];
  34658. var nbfaces = data.face.length;
  34659. var faceUV = options.faceUV || new Array(nbfaces);
  34660. var faceColors = options.faceColors;
  34661. var flat = (options.flat === undefined) ? true : options.flat;
  34662. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34663. var positions = new Array();
  34664. var indices = new Array();
  34665. var normals = new Array();
  34666. var uvs = new Array();
  34667. var colors = new Array();
  34668. var index = 0;
  34669. var faceIdx = 0; // face cursor in the array "indexes"
  34670. var indexes = new Array();
  34671. var i = 0;
  34672. var f = 0;
  34673. var u, v, ang, x, y, tmp;
  34674. // default face colors and UV if undefined
  34675. if (flat) {
  34676. for (f = 0; f < nbfaces; f++) {
  34677. if (faceColors && faceColors[f] === undefined) {
  34678. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34679. }
  34680. if (faceUV && faceUV[f] === undefined) {
  34681. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34682. }
  34683. }
  34684. }
  34685. if (!flat) {
  34686. for (i = 0; i < data.vertex.length; i++) {
  34687. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34688. uvs.push(0, 0);
  34689. }
  34690. for (f = 0; f < nbfaces; f++) {
  34691. for (i = 0; i < data.face[f].length - 2; i++) {
  34692. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34693. }
  34694. }
  34695. }
  34696. else {
  34697. for (f = 0; f < nbfaces; f++) {
  34698. var fl = data.face[f].length; // number of vertices of the current face
  34699. ang = 2 * Math.PI / fl;
  34700. x = 0.5 * Math.tan(ang / 2);
  34701. y = 0.5;
  34702. // positions, uvs, colors
  34703. for (i = 0; i < fl; i++) {
  34704. // positions
  34705. 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);
  34706. indexes.push(index);
  34707. index++;
  34708. // uvs
  34709. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34710. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34711. uvs.push(u, v);
  34712. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34713. y = x * Math.sin(ang) + y * Math.cos(ang);
  34714. x = tmp;
  34715. // colors
  34716. if (faceColors) {
  34717. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34718. }
  34719. }
  34720. // indices from indexes
  34721. for (i = 0; i < fl - 2; i++) {
  34722. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34723. }
  34724. faceIdx += fl;
  34725. }
  34726. }
  34727. VertexData.ComputeNormals(positions, indices, normals);
  34728. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34729. var vertexData = new VertexData();
  34730. vertexData.positions = positions;
  34731. vertexData.indices = indices;
  34732. vertexData.normals = normals;
  34733. vertexData.uvs = uvs;
  34734. if (faceColors && flat) {
  34735. vertexData.colors = colors;
  34736. }
  34737. return vertexData;
  34738. };
  34739. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34740. /**
  34741. * Creates the VertexData of the Torus Knot.
  34742. */
  34743. VertexData.CreateTorusKnot = function (options) {
  34744. var indices = new Array();
  34745. var positions = new Array();
  34746. var normals = new Array();
  34747. var uvs = new Array();
  34748. var radius = options.radius || 2;
  34749. var tube = options.tube || 0.5;
  34750. var radialSegments = options.radialSegments || 32;
  34751. var tubularSegments = options.tubularSegments || 32;
  34752. var p = options.p || 2;
  34753. var q = options.q || 3;
  34754. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34755. // Helper
  34756. var getPos = function (angle) {
  34757. var cu = Math.cos(angle);
  34758. var su = Math.sin(angle);
  34759. var quOverP = q / p * angle;
  34760. var cs = Math.cos(quOverP);
  34761. var tx = radius * (2 + cs) * 0.5 * cu;
  34762. var ty = radius * (2 + cs) * su * 0.5;
  34763. var tz = radius * Math.sin(quOverP) * 0.5;
  34764. return new BABYLON.Vector3(tx, ty, tz);
  34765. };
  34766. // Vertices
  34767. var i;
  34768. var j;
  34769. for (i = 0; i <= radialSegments; i++) {
  34770. var modI = i % radialSegments;
  34771. var u = modI / radialSegments * 2 * p * Math.PI;
  34772. var p1 = getPos(u);
  34773. var p2 = getPos(u + 0.01);
  34774. var tang = p2.subtract(p1);
  34775. var n = p2.add(p1);
  34776. var bitan = BABYLON.Vector3.Cross(tang, n);
  34777. n = BABYLON.Vector3.Cross(bitan, tang);
  34778. bitan.normalize();
  34779. n.normalize();
  34780. for (j = 0; j < tubularSegments; j++) {
  34781. var modJ = j % tubularSegments;
  34782. var v = modJ / tubularSegments * 2 * Math.PI;
  34783. var cx = -tube * Math.cos(v);
  34784. var cy = tube * Math.sin(v);
  34785. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34786. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34787. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34788. uvs.push(i / radialSegments);
  34789. uvs.push(j / tubularSegments);
  34790. }
  34791. }
  34792. for (i = 0; i < radialSegments; i++) {
  34793. for (j = 0; j < tubularSegments; j++) {
  34794. var jNext = (j + 1) % tubularSegments;
  34795. var a = i * tubularSegments + j;
  34796. var b = (i + 1) * tubularSegments + j;
  34797. var c = (i + 1) * tubularSegments + jNext;
  34798. var d = i * tubularSegments + jNext;
  34799. indices.push(d);
  34800. indices.push(b);
  34801. indices.push(a);
  34802. indices.push(d);
  34803. indices.push(c);
  34804. indices.push(b);
  34805. }
  34806. }
  34807. // Normals
  34808. VertexData.ComputeNormals(positions, indices, normals);
  34809. // Sides
  34810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34811. // Result
  34812. var vertexData = new VertexData();
  34813. vertexData.indices = indices;
  34814. vertexData.positions = positions;
  34815. vertexData.normals = normals;
  34816. vertexData.uvs = uvs;
  34817. return vertexData;
  34818. };
  34819. // Tools
  34820. /**
  34821. * @param {any} - positions (number[] or Float32Array)
  34822. * @param {any} - indices (number[] or Uint16Array)
  34823. * @param {any} - normals (number[] or Float32Array)
  34824. * options (optional) :
  34825. * facetPositions : optional array of facet positions (vector3)
  34826. * facetNormals : optional array of facet normals (vector3)
  34827. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34828. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34829. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34830. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34831. * bInfo : optional bounding info, required for facetPartitioning computation
  34832. * useRightHandedSystem: optional boolean to for right handed system computation
  34833. * depthSort : optional boolean to enable the facet depth sort computation
  34834. * distanceTo : optional Vector3 to compute the facet depth from this location
  34835. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34836. */
  34837. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34838. // temporary scalar variables
  34839. var index = 0; // facet index
  34840. var p1p2x = 0.0; // p1p2 vector x coordinate
  34841. var p1p2y = 0.0; // p1p2 vector y coordinate
  34842. var p1p2z = 0.0; // p1p2 vector z coordinate
  34843. var p3p2x = 0.0; // p3p2 vector x coordinate
  34844. var p3p2y = 0.0; // p3p2 vector y coordinate
  34845. var p3p2z = 0.0; // p3p2 vector z coordinate
  34846. var faceNormalx = 0.0; // facet normal x coordinate
  34847. var faceNormaly = 0.0; // facet normal y coordinate
  34848. var faceNormalz = 0.0; // facet normal z coordinate
  34849. var length = 0.0; // facet normal length before normalization
  34850. var v1x = 0; // vector1 x index in the positions array
  34851. var v1y = 0; // vector1 y index in the positions array
  34852. var v1z = 0; // vector1 z index in the positions array
  34853. var v2x = 0; // vector2 x index in the positions array
  34854. var v2y = 0; // vector2 y index in the positions array
  34855. var v2z = 0; // vector2 z index in the positions array
  34856. var v3x = 0; // vector3 x index in the positions array
  34857. var v3y = 0; // vector3 y index in the positions array
  34858. var v3z = 0; // vector3 z index in the positions array
  34859. var computeFacetNormals = false;
  34860. var computeFacetPositions = false;
  34861. var computeFacetPartitioning = false;
  34862. var computeDepthSort = false;
  34863. var faceNormalSign = 1;
  34864. var ratio = 0;
  34865. var distanceTo = null;
  34866. if (options) {
  34867. computeFacetNormals = (options.facetNormals) ? true : false;
  34868. computeFacetPositions = (options.facetPositions) ? true : false;
  34869. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34870. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34871. ratio = options.ratio || 0;
  34872. computeDepthSort = (options.depthSort) ? true : false;
  34873. distanceTo = (options.distanceTo);
  34874. if (computeDepthSort) {
  34875. if (distanceTo === undefined) {
  34876. distanceTo = BABYLON.Vector3.Zero();
  34877. }
  34878. var depthSortedFacets = options.depthSortedFacets;
  34879. }
  34880. }
  34881. // facetPartitioning reinit if needed
  34882. var xSubRatio = 0;
  34883. var ySubRatio = 0;
  34884. var zSubRatio = 0;
  34885. var subSq = 0;
  34886. if (computeFacetPartitioning && options && options.bbSize) {
  34887. var ox = 0; // X partitioning index for facet position
  34888. var oy = 0; // Y partinioning index for facet position
  34889. var oz = 0; // Z partinioning index for facet position
  34890. var b1x = 0; // X partitioning index for facet v1 vertex
  34891. var b1y = 0; // Y partitioning index for facet v1 vertex
  34892. var b1z = 0; // z partitioning index for facet v1 vertex
  34893. var b2x = 0; // X partitioning index for facet v2 vertex
  34894. var b2y = 0; // Y partitioning index for facet v2 vertex
  34895. var b2z = 0; // Z partitioning index for facet v2 vertex
  34896. var b3x = 0; // X partitioning index for facet v3 vertex
  34897. var b3y = 0; // Y partitioning index for facet v3 vertex
  34898. var b3z = 0; // Z partitioning index for facet v3 vertex
  34899. var block_idx_o = 0; // facet barycenter block index
  34900. var block_idx_v1 = 0; // v1 vertex block index
  34901. var block_idx_v2 = 0; // v2 vertex block index
  34902. var block_idx_v3 = 0; // v3 vertex block index
  34903. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34904. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34905. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34906. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34907. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34908. subSq = options.subDiv.max * options.subDiv.max;
  34909. options.facetPartitioning.length = 0;
  34910. }
  34911. // reset the normals
  34912. for (index = 0; index < positions.length; index++) {
  34913. normals[index] = 0.0;
  34914. }
  34915. // Loop : 1 indice triplet = 1 facet
  34916. var nbFaces = (indices.length / 3) | 0;
  34917. for (index = 0; index < nbFaces; index++) {
  34918. // get the indexes of the coordinates of each vertex of the facet
  34919. v1x = indices[index * 3] * 3;
  34920. v1y = v1x + 1;
  34921. v1z = v1x + 2;
  34922. v2x = indices[index * 3 + 1] * 3;
  34923. v2y = v2x + 1;
  34924. v2z = v2x + 2;
  34925. v3x = indices[index * 3 + 2] * 3;
  34926. v3y = v3x + 1;
  34927. v3z = v3x + 2;
  34928. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34929. p1p2y = positions[v1y] - positions[v2y];
  34930. p1p2z = positions[v1z] - positions[v2z];
  34931. p3p2x = positions[v3x] - positions[v2x];
  34932. p3p2y = positions[v3y] - positions[v2y];
  34933. p3p2z = positions[v3z] - positions[v2z];
  34934. // compute the face normal with the cross product
  34935. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34936. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34937. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34938. // normalize this normal and store it in the array facetData
  34939. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34940. length = (length === 0) ? 1.0 : length;
  34941. faceNormalx /= length;
  34942. faceNormaly /= length;
  34943. faceNormalz /= length;
  34944. if (computeFacetNormals && options) {
  34945. options.facetNormals[index].x = faceNormalx;
  34946. options.facetNormals[index].y = faceNormaly;
  34947. options.facetNormals[index].z = faceNormalz;
  34948. }
  34949. if (computeFacetPositions && options) {
  34950. // compute and the facet barycenter coordinates in the array facetPositions
  34951. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34952. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34953. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34954. }
  34955. if (computeFacetPartitioning && options) {
  34956. // store the facet indexes in arrays in the main facetPartitioning array :
  34957. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34958. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34959. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34960. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34961. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34962. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34963. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34964. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34965. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34966. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34967. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34968. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34969. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34970. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34971. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34972. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34973. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34974. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34975. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34976. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34977. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34978. // push each facet index in each block containing the vertex
  34979. options.facetPartitioning[block_idx_v1].push(index);
  34980. if (block_idx_v2 != block_idx_v1) {
  34981. options.facetPartitioning[block_idx_v2].push(index);
  34982. }
  34983. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34984. options.facetPartitioning[block_idx_v3].push(index);
  34985. }
  34986. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34987. options.facetPartitioning[block_idx_o].push(index);
  34988. }
  34989. }
  34990. if (computeDepthSort && options && options.facetPositions) {
  34991. var dsf = depthSortedFacets[index];
  34992. dsf.ind = index * 3;
  34993. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34994. }
  34995. // compute the normals anyway
  34996. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34997. normals[v1y] += faceNormaly;
  34998. normals[v1z] += faceNormalz;
  34999. normals[v2x] += faceNormalx;
  35000. normals[v2y] += faceNormaly;
  35001. normals[v2z] += faceNormalz;
  35002. normals[v3x] += faceNormalx;
  35003. normals[v3y] += faceNormaly;
  35004. normals[v3z] += faceNormalz;
  35005. }
  35006. // last normalization of each normal
  35007. for (index = 0; index < normals.length / 3; index++) {
  35008. faceNormalx = normals[index * 3];
  35009. faceNormaly = normals[index * 3 + 1];
  35010. faceNormalz = normals[index * 3 + 2];
  35011. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35012. length = (length === 0) ? 1.0 : length;
  35013. faceNormalx /= length;
  35014. faceNormaly /= length;
  35015. faceNormalz /= length;
  35016. normals[index * 3] = faceNormalx;
  35017. normals[index * 3 + 1] = faceNormaly;
  35018. normals[index * 3 + 2] = faceNormalz;
  35019. }
  35020. };
  35021. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  35022. var li = indices.length;
  35023. var ln = normals.length;
  35024. var i;
  35025. var n;
  35026. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35027. switch (sideOrientation) {
  35028. case BABYLON.Mesh.FRONTSIDE:
  35029. // nothing changed
  35030. break;
  35031. case BABYLON.Mesh.BACKSIDE:
  35032. var tmp;
  35033. // indices
  35034. for (i = 0; i < li; i += 3) {
  35035. tmp = indices[i];
  35036. indices[i] = indices[i + 2];
  35037. indices[i + 2] = tmp;
  35038. }
  35039. // normals
  35040. for (n = 0; n < ln; n++) {
  35041. normals[n] = -normals[n];
  35042. }
  35043. break;
  35044. case BABYLON.Mesh.DOUBLESIDE:
  35045. // positions
  35046. var lp = positions.length;
  35047. var l = lp / 3;
  35048. for (var p = 0; p < lp; p++) {
  35049. positions[lp + p] = positions[p];
  35050. }
  35051. // indices
  35052. for (i = 0; i < li; i += 3) {
  35053. indices[i + li] = indices[i + 2] + l;
  35054. indices[i + 1 + li] = indices[i + 1] + l;
  35055. indices[i + 2 + li] = indices[i] + l;
  35056. }
  35057. // normals
  35058. for (n = 0; n < ln; n++) {
  35059. normals[ln + n] = -normals[n];
  35060. }
  35061. // uvs
  35062. var lu = uvs.length;
  35063. var u = 0;
  35064. for (u = 0; u < lu; u++) {
  35065. uvs[u + lu] = uvs[u];
  35066. }
  35067. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35068. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35069. u = 0;
  35070. for (i = 0; i < lu / 2; i++) {
  35071. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35072. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35073. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35074. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35075. u += 2;
  35076. }
  35077. break;
  35078. }
  35079. };
  35080. /**
  35081. * Creates a new VertexData from the imported parameters.
  35082. */
  35083. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35084. var vertexData = new VertexData();
  35085. // positions
  35086. var positions = parsedVertexData.positions;
  35087. if (positions) {
  35088. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35089. }
  35090. // normals
  35091. var normals = parsedVertexData.normals;
  35092. if (normals) {
  35093. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35094. }
  35095. // tangents
  35096. var tangents = parsedVertexData.tangents;
  35097. if (tangents) {
  35098. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35099. }
  35100. // uvs
  35101. var uvs = parsedVertexData.uvs;
  35102. if (uvs) {
  35103. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35104. }
  35105. // uv2s
  35106. var uv2s = parsedVertexData.uv2s;
  35107. if (uv2s) {
  35108. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35109. }
  35110. // uv3s
  35111. var uv3s = parsedVertexData.uv3s;
  35112. if (uv3s) {
  35113. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35114. }
  35115. // uv4s
  35116. var uv4s = parsedVertexData.uv4s;
  35117. if (uv4s) {
  35118. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35119. }
  35120. // uv5s
  35121. var uv5s = parsedVertexData.uv5s;
  35122. if (uv5s) {
  35123. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35124. }
  35125. // uv6s
  35126. var uv6s = parsedVertexData.uv6s;
  35127. if (uv6s) {
  35128. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35129. }
  35130. // colors
  35131. var colors = parsedVertexData.colors;
  35132. if (colors) {
  35133. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35134. }
  35135. // matricesIndices
  35136. var matricesIndices = parsedVertexData.matricesIndices;
  35137. if (matricesIndices) {
  35138. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35139. }
  35140. // matricesWeights
  35141. var matricesWeights = parsedVertexData.matricesWeights;
  35142. if (matricesWeights) {
  35143. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35144. }
  35145. // indices
  35146. var indices = parsedVertexData.indices;
  35147. if (indices) {
  35148. vertexData.indices = indices;
  35149. }
  35150. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35151. };
  35152. return VertexData;
  35153. }());
  35154. BABYLON.VertexData = VertexData;
  35155. })(BABYLON || (BABYLON = {}));
  35156. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35157. "use strict";
  35158. var BABYLON;
  35159. (function (BABYLON) {
  35160. /**
  35161. * Class used to store geometry data (vertex buffers + index buffer)
  35162. */
  35163. var Geometry = /** @class */ (function () {
  35164. /**
  35165. * Creates a new geometry
  35166. * @param id defines the unique ID
  35167. * @param scene defines the hosting scene
  35168. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35169. * @param updatable defines if geometry must be updatable (false by default)
  35170. * @param mesh defines the mesh that will be associated with the geometry
  35171. */
  35172. function Geometry(id, scene, vertexData, updatable, mesh) {
  35173. if (updatable === void 0) { updatable = false; }
  35174. if (mesh === void 0) { mesh = null; }
  35175. /**
  35176. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35177. */
  35178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35179. this._totalVertices = 0;
  35180. this._isDisposed = false;
  35181. this._indexBufferIsUpdatable = false;
  35182. this.id = id;
  35183. this._engine = scene.getEngine();
  35184. this._meshes = [];
  35185. this._scene = scene;
  35186. //Init vertex buffer cache
  35187. this._vertexBuffers = {};
  35188. this._indices = [];
  35189. this._updatable = updatable;
  35190. // vertexData
  35191. if (vertexData) {
  35192. this.setAllVerticesData(vertexData, updatable);
  35193. }
  35194. else {
  35195. this._totalVertices = 0;
  35196. this._indices = [];
  35197. }
  35198. if (this._engine.getCaps().vertexArrayObject) {
  35199. this._vertexArrayObjects = {};
  35200. }
  35201. // applyToMesh
  35202. if (mesh) {
  35203. if (mesh.getClassName() === "LinesMesh") {
  35204. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35205. this.updateExtend();
  35206. }
  35207. this.applyToMesh(mesh);
  35208. mesh.computeWorldMatrix(true);
  35209. }
  35210. }
  35211. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35212. /**
  35213. * 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
  35214. */
  35215. get: function () {
  35216. return this._boundingBias;
  35217. },
  35218. /**
  35219. * 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
  35220. */
  35221. set: function (value) {
  35222. if (this._boundingBias && this._boundingBias.equals(value)) {
  35223. return;
  35224. }
  35225. this._boundingBias = value.clone();
  35226. this.updateBoundingInfo(true, null);
  35227. },
  35228. enumerable: true,
  35229. configurable: true
  35230. });
  35231. /**
  35232. * Static function used to attach a new empty geometry to a mesh
  35233. * @param mesh defines the mesh to attach the geometry to
  35234. * @returns the new {BABYLON.Geometry}
  35235. */
  35236. Geometry.CreateGeometryForMesh = function (mesh) {
  35237. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35238. geometry.applyToMesh(mesh);
  35239. return geometry;
  35240. };
  35241. Object.defineProperty(Geometry.prototype, "extend", {
  35242. /**
  35243. * Gets the current extend of the geometry
  35244. */
  35245. get: function () {
  35246. return this._extend;
  35247. },
  35248. enumerable: true,
  35249. configurable: true
  35250. });
  35251. /**
  35252. * Gets the hosting scene
  35253. * @returns the hosting {BABYLON.Scene}
  35254. */
  35255. Geometry.prototype.getScene = function () {
  35256. return this._scene;
  35257. };
  35258. /**
  35259. * Gets the hosting engine
  35260. * @returns the hosting {BABYLON.Engine}
  35261. */
  35262. Geometry.prototype.getEngine = function () {
  35263. return this._engine;
  35264. };
  35265. /**
  35266. * Defines if the geometry is ready to use
  35267. * @returns true if the geometry is ready to be used
  35268. */
  35269. Geometry.prototype.isReady = function () {
  35270. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35271. };
  35272. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35273. /**
  35274. * Gets a value indicating that the geometry should not be serialized
  35275. */
  35276. get: function () {
  35277. for (var index = 0; index < this._meshes.length; index++) {
  35278. if (!this._meshes[index].doNotSerialize) {
  35279. return false;
  35280. }
  35281. }
  35282. return true;
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. /** @ignore */
  35288. Geometry.prototype._rebuild = function () {
  35289. if (this._vertexArrayObjects) {
  35290. this._vertexArrayObjects = {};
  35291. }
  35292. // Index buffer
  35293. if (this._meshes.length !== 0 && this._indices) {
  35294. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35295. }
  35296. // Vertex buffers
  35297. for (var key in this._vertexBuffers) {
  35298. var vertexBuffer = this._vertexBuffers[key];
  35299. vertexBuffer._rebuild();
  35300. }
  35301. };
  35302. /**
  35303. * Affects all gemetry data in one call
  35304. * @param vertexData defines the geometry data
  35305. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35306. */
  35307. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35308. vertexData.applyToGeometry(this, updatable);
  35309. this.notifyUpdate();
  35310. };
  35311. /**
  35312. * Set specific vertex data
  35313. * @param kind defines the data kind (Position, normal, etc...)
  35314. * @param data defines the vertex data to use
  35315. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35316. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35317. */
  35318. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35319. if (updatable === void 0) { updatable = false; }
  35320. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35321. this.setVerticesBuffer(buffer);
  35322. };
  35323. /**
  35324. * Removes a specific vertex data
  35325. * @param kind defines the data kind (Position, normal, etc...)
  35326. */
  35327. Geometry.prototype.removeVerticesData = function (kind) {
  35328. if (this._vertexBuffers[kind]) {
  35329. this._vertexBuffers[kind].dispose();
  35330. delete this._vertexBuffers[kind];
  35331. }
  35332. };
  35333. /**
  35334. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35335. * @param buffer defines the vertex buffer to use
  35336. */
  35337. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35338. var kind = buffer.getKind();
  35339. if (this._vertexBuffers[kind]) {
  35340. this._vertexBuffers[kind].dispose();
  35341. }
  35342. this._vertexBuffers[kind] = buffer;
  35343. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35344. var data = buffer.getData();
  35345. var stride = buffer.getStrideSize();
  35346. this._totalVertices = data.length / stride;
  35347. this.updateExtend(data, stride);
  35348. this._resetPointsArrayCache();
  35349. var meshes = this._meshes;
  35350. var numOfMeshes = meshes.length;
  35351. for (var index = 0; index < numOfMeshes; index++) {
  35352. var mesh = meshes[index];
  35353. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35354. mesh._createGlobalSubMesh(false);
  35355. mesh.computeWorldMatrix(true);
  35356. }
  35357. }
  35358. this.notifyUpdate(kind);
  35359. if (this._vertexArrayObjects) {
  35360. this._disposeVertexArrayObjects();
  35361. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35362. }
  35363. };
  35364. /**
  35365. * Update a specific vertex buffer
  35366. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35367. * It will do nothing if the buffer is not updatable
  35368. * @param kind defines the data kind (Position, normal, etc...)
  35369. * @param data defines the data to use
  35370. * @param offset defines the offset in the target buffer where to store the data
  35371. */
  35372. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35373. var vertexBuffer = this.getVertexBuffer(kind);
  35374. if (!vertexBuffer) {
  35375. return;
  35376. }
  35377. vertexBuffer.updateDirectly(data, offset);
  35378. this.notifyUpdate(kind);
  35379. };
  35380. /**
  35381. * Update a specific vertex buffer
  35382. * This function will create a new buffer if the current one is not updatable
  35383. * @param kind defines the data kind (Position, normal, etc...)
  35384. * @param data defines the data to use
  35385. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35386. */
  35387. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35388. if (updateExtends === void 0) { updateExtends = false; }
  35389. var vertexBuffer = this.getVertexBuffer(kind);
  35390. if (!vertexBuffer) {
  35391. return;
  35392. }
  35393. vertexBuffer.update(data);
  35394. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35395. var stride = vertexBuffer.getStrideSize();
  35396. this._totalVertices = data.length / stride;
  35397. this.updateBoundingInfo(updateExtends, data);
  35398. }
  35399. this.notifyUpdate(kind);
  35400. };
  35401. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35402. if (updateExtends) {
  35403. this.updateExtend(data);
  35404. }
  35405. var meshes = this._meshes;
  35406. var numOfMeshes = meshes.length;
  35407. this._resetPointsArrayCache();
  35408. for (var index = 0; index < numOfMeshes; index++) {
  35409. var mesh = meshes[index];
  35410. if (updateExtends) {
  35411. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35412. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35413. var subMesh = mesh.subMeshes[subIndex];
  35414. subMesh.refreshBoundingInfo();
  35415. }
  35416. }
  35417. }
  35418. };
  35419. /** @ignore */
  35420. Geometry.prototype._bind = function (effect, indexToBind) {
  35421. if (!effect) {
  35422. return;
  35423. }
  35424. if (indexToBind === undefined) {
  35425. indexToBind = this._indexBuffer;
  35426. }
  35427. var vbs = this.getVertexBuffers();
  35428. if (!vbs) {
  35429. return;
  35430. }
  35431. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35432. this._engine.bindBuffers(vbs, indexToBind, effect);
  35433. return;
  35434. }
  35435. // Using VAO
  35436. if (!this._vertexArrayObjects[effect.key]) {
  35437. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35438. }
  35439. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35440. };
  35441. /**
  35442. * Gets total number of vertices
  35443. * @returns the total number of vertices
  35444. */
  35445. Geometry.prototype.getTotalVertices = function () {
  35446. if (!this.isReady()) {
  35447. return 0;
  35448. }
  35449. return this._totalVertices;
  35450. };
  35451. /**
  35452. * Gets a specific vertex data attached to this geometry
  35453. * @param kind defines the data kind (Position, normal, etc...)
  35454. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35455. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35456. * @returns a float array containing vertex data
  35457. */
  35458. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35459. var vertexBuffer = this.getVertexBuffer(kind);
  35460. if (!vertexBuffer) {
  35461. return null;
  35462. }
  35463. var orig = vertexBuffer.getData();
  35464. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35465. return orig;
  35466. }
  35467. else {
  35468. var len = orig.length;
  35469. var copy = [];
  35470. for (var i = 0; i < len; i++) {
  35471. copy.push(orig[i]);
  35472. }
  35473. return copy;
  35474. }
  35475. };
  35476. /**
  35477. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35478. * @param kind defines the data kind (Position, normal, etc...)
  35479. * @returns true if the vertex buffer with the specified kind is updatable
  35480. */
  35481. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35482. var vb = this._vertexBuffers[kind];
  35483. if (!vb) {
  35484. return false;
  35485. }
  35486. return vb.isUpdatable();
  35487. };
  35488. /**
  35489. * Gets a specific vertex buffer
  35490. * @param kind defines the data kind (Position, normal, etc...)
  35491. * @returns a {BABYLON.VertexBuffer}
  35492. */
  35493. Geometry.prototype.getVertexBuffer = function (kind) {
  35494. if (!this.isReady()) {
  35495. return null;
  35496. }
  35497. return this._vertexBuffers[kind];
  35498. };
  35499. /**
  35500. * Returns all vertex buffers
  35501. * @return an object holding all vertex buffers indexed by kind
  35502. */
  35503. Geometry.prototype.getVertexBuffers = function () {
  35504. if (!this.isReady()) {
  35505. return null;
  35506. }
  35507. return this._vertexBuffers;
  35508. };
  35509. /**
  35510. * Gets a boolean indicating if specific vertex buffer is present
  35511. * @param kind defines the data kind (Position, normal, etc...)
  35512. * @returns true if data is present
  35513. */
  35514. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35515. if (!this._vertexBuffers) {
  35516. if (this._delayInfo) {
  35517. return this._delayInfo.indexOf(kind) !== -1;
  35518. }
  35519. return false;
  35520. }
  35521. return this._vertexBuffers[kind] !== undefined;
  35522. };
  35523. /**
  35524. * Gets a list of all attached data kinds (Position, normal, etc...)
  35525. * @returns a list of string containing all kinds
  35526. */
  35527. Geometry.prototype.getVerticesDataKinds = function () {
  35528. var result = [];
  35529. var kind;
  35530. if (!this._vertexBuffers && this._delayInfo) {
  35531. for (kind in this._delayInfo) {
  35532. result.push(kind);
  35533. }
  35534. }
  35535. else {
  35536. for (kind in this._vertexBuffers) {
  35537. result.push(kind);
  35538. }
  35539. }
  35540. return result;
  35541. };
  35542. /**
  35543. * Update index buffer
  35544. * @param indices defines the indices to store in the index buffer
  35545. * @param offset defines the offset in the target buffer where to store the data
  35546. */
  35547. Geometry.prototype.updateIndices = function (indices, offset) {
  35548. if (!this._indexBuffer) {
  35549. return;
  35550. }
  35551. if (!this._indexBufferIsUpdatable) {
  35552. this.setIndices(indices, null, true);
  35553. }
  35554. else {
  35555. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35556. }
  35557. };
  35558. /**
  35559. * Creates a new index buffer
  35560. * @param indices defines the indices to store in the index buffer
  35561. * @param totalVertices defines the total number of vertices (could be null)
  35562. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35563. */
  35564. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35565. if (totalVertices === void 0) { totalVertices = null; }
  35566. if (updatable === void 0) { updatable = false; }
  35567. if (this._indexBuffer) {
  35568. this._engine._releaseBuffer(this._indexBuffer);
  35569. }
  35570. this._disposeVertexArrayObjects();
  35571. this._indices = indices;
  35572. this._indexBufferIsUpdatable = updatable;
  35573. if (this._meshes.length !== 0 && this._indices) {
  35574. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35575. }
  35576. if (totalVertices != undefined) {
  35577. this._totalVertices = totalVertices;
  35578. }
  35579. var meshes = this._meshes;
  35580. var numOfMeshes = meshes.length;
  35581. for (var index = 0; index < numOfMeshes; index++) {
  35582. meshes[index]._createGlobalSubMesh(true);
  35583. }
  35584. this.notifyUpdate();
  35585. };
  35586. /**
  35587. * Return the total number of indices
  35588. * @returns the total number of indices
  35589. */
  35590. Geometry.prototype.getTotalIndices = function () {
  35591. if (!this.isReady()) {
  35592. return 0;
  35593. }
  35594. return this._indices.length;
  35595. };
  35596. /**
  35597. * Gets the index buffer array
  35598. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35599. * @returns the index buffer array
  35600. */
  35601. Geometry.prototype.getIndices = function (copyWhenShared) {
  35602. if (!this.isReady()) {
  35603. return null;
  35604. }
  35605. var orig = this._indices;
  35606. if (!copyWhenShared || this._meshes.length === 1) {
  35607. return orig;
  35608. }
  35609. else {
  35610. var len = orig.length;
  35611. var copy = [];
  35612. for (var i = 0; i < len; i++) {
  35613. copy.push(orig[i]);
  35614. }
  35615. return copy;
  35616. }
  35617. };
  35618. /**
  35619. * Gets the index buffer
  35620. * @return the index buffer
  35621. */
  35622. Geometry.prototype.getIndexBuffer = function () {
  35623. if (!this.isReady()) {
  35624. return null;
  35625. }
  35626. return this._indexBuffer;
  35627. };
  35628. /** @ignore */
  35629. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35630. if (effect === void 0) { effect = null; }
  35631. if (!effect || !this._vertexArrayObjects) {
  35632. return;
  35633. }
  35634. if (this._vertexArrayObjects[effect.key]) {
  35635. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35636. delete this._vertexArrayObjects[effect.key];
  35637. }
  35638. };
  35639. /**
  35640. * Release the associated resources for a specific mesh
  35641. * @param mesh defines the source mesh
  35642. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35643. */
  35644. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35645. var meshes = this._meshes;
  35646. var index = meshes.indexOf(mesh);
  35647. if (index === -1) {
  35648. return;
  35649. }
  35650. meshes.splice(index, 1);
  35651. mesh._geometry = null;
  35652. if (meshes.length === 0 && shouldDispose) {
  35653. this.dispose();
  35654. }
  35655. };
  35656. /**
  35657. * Apply current geometry to a given mesh
  35658. * @param mesh defines the mesh to apply geometry to
  35659. */
  35660. Geometry.prototype.applyToMesh = function (mesh) {
  35661. if (mesh._geometry === this) {
  35662. return;
  35663. }
  35664. var previousGeometry = mesh._geometry;
  35665. if (previousGeometry) {
  35666. previousGeometry.releaseForMesh(mesh);
  35667. }
  35668. var meshes = this._meshes;
  35669. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35670. mesh._geometry = this;
  35671. this._scene.pushGeometry(this);
  35672. meshes.push(mesh);
  35673. if (this.isReady()) {
  35674. this._applyToMesh(mesh);
  35675. }
  35676. else {
  35677. mesh._boundingInfo = this._boundingInfo;
  35678. }
  35679. };
  35680. Geometry.prototype.updateExtend = function (data, stride) {
  35681. if (data === void 0) { data = null; }
  35682. if (!data) {
  35683. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35684. }
  35685. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35686. };
  35687. Geometry.prototype._applyToMesh = function (mesh) {
  35688. var numOfMeshes = this._meshes.length;
  35689. // vertexBuffers
  35690. for (var kind in this._vertexBuffers) {
  35691. if (numOfMeshes === 1) {
  35692. this._vertexBuffers[kind].create();
  35693. }
  35694. var buffer = this._vertexBuffers[kind].getBuffer();
  35695. if (buffer)
  35696. buffer.references = numOfMeshes;
  35697. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35698. if (!this._extend) {
  35699. this.updateExtend(this._vertexBuffers[kind].getData());
  35700. }
  35701. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35702. mesh._createGlobalSubMesh(false);
  35703. //bounding info was just created again, world matrix should be applied again.
  35704. mesh._updateBoundingInfo();
  35705. }
  35706. }
  35707. // indexBuffer
  35708. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35709. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35710. }
  35711. if (this._indexBuffer) {
  35712. this._indexBuffer.references = numOfMeshes;
  35713. }
  35714. };
  35715. Geometry.prototype.notifyUpdate = function (kind) {
  35716. if (this.onGeometryUpdated) {
  35717. this.onGeometryUpdated(this, kind);
  35718. }
  35719. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35720. var mesh = _a[_i];
  35721. mesh._markSubMeshesAsAttributesDirty();
  35722. }
  35723. };
  35724. /**
  35725. * Load the geometry if it was flagged as delay loaded
  35726. * @param scene defines the hosting scene
  35727. * @param onLoaded defines a callback called when the geometry is loaded
  35728. */
  35729. Geometry.prototype.load = function (scene, onLoaded) {
  35730. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35731. return;
  35732. }
  35733. if (this.isReady()) {
  35734. if (onLoaded) {
  35735. onLoaded();
  35736. }
  35737. return;
  35738. }
  35739. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35740. this._queueLoad(scene, onLoaded);
  35741. };
  35742. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35743. var _this = this;
  35744. if (!this.delayLoadingFile) {
  35745. return;
  35746. }
  35747. scene._addPendingData(this);
  35748. scene._loadFile(this.delayLoadingFile, function (data) {
  35749. if (!_this._delayLoadingFunction) {
  35750. return;
  35751. }
  35752. _this._delayLoadingFunction(JSON.parse(data), _this);
  35753. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35754. _this._delayInfo = [];
  35755. scene._removePendingData(_this);
  35756. var meshes = _this._meshes;
  35757. var numOfMeshes = meshes.length;
  35758. for (var index = 0; index < numOfMeshes; index++) {
  35759. _this._applyToMesh(meshes[index]);
  35760. }
  35761. if (onLoaded) {
  35762. onLoaded();
  35763. }
  35764. }, undefined, true);
  35765. };
  35766. /**
  35767. * Invert the geometry to move from a right handed system to a left handed one.
  35768. */
  35769. Geometry.prototype.toLeftHanded = function () {
  35770. // Flip faces
  35771. var tIndices = this.getIndices(false);
  35772. if (tIndices != null && tIndices.length > 0) {
  35773. for (var i = 0; i < tIndices.length; i += 3) {
  35774. var tTemp = tIndices[i + 0];
  35775. tIndices[i + 0] = tIndices[i + 2];
  35776. tIndices[i + 2] = tTemp;
  35777. }
  35778. this.setIndices(tIndices);
  35779. }
  35780. // Negate position.z
  35781. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35782. if (tPositions != null && tPositions.length > 0) {
  35783. for (var i = 0; i < tPositions.length; i += 3) {
  35784. tPositions[i + 2] = -tPositions[i + 2];
  35785. }
  35786. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35787. }
  35788. // Negate normal.z
  35789. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35790. if (tNormals != null && tNormals.length > 0) {
  35791. for (var i = 0; i < tNormals.length; i += 3) {
  35792. tNormals[i + 2] = -tNormals[i + 2];
  35793. }
  35794. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35795. }
  35796. };
  35797. // Cache
  35798. /** @ignore */
  35799. Geometry.prototype._resetPointsArrayCache = function () {
  35800. this._positions = null;
  35801. };
  35802. /** @ignore */
  35803. Geometry.prototype._generatePointsArray = function () {
  35804. if (this._positions)
  35805. return true;
  35806. this._positions = [];
  35807. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35808. if (!data) {
  35809. return false;
  35810. }
  35811. for (var index = 0; index < data.length; index += 3) {
  35812. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35813. }
  35814. return true;
  35815. };
  35816. /**
  35817. * Gets a value indicating if the geometry is disposed
  35818. * @returns true if the geometry was disposed
  35819. */
  35820. Geometry.prototype.isDisposed = function () {
  35821. return this._isDisposed;
  35822. };
  35823. Geometry.prototype._disposeVertexArrayObjects = function () {
  35824. if (this._vertexArrayObjects) {
  35825. for (var kind in this._vertexArrayObjects) {
  35826. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35827. }
  35828. this._vertexArrayObjects = {};
  35829. }
  35830. };
  35831. /**
  35832. * Free all associated resources
  35833. */
  35834. Geometry.prototype.dispose = function () {
  35835. var meshes = this._meshes;
  35836. var numOfMeshes = meshes.length;
  35837. var index;
  35838. for (index = 0; index < numOfMeshes; index++) {
  35839. this.releaseForMesh(meshes[index]);
  35840. }
  35841. this._meshes = [];
  35842. this._disposeVertexArrayObjects();
  35843. for (var kind in this._vertexBuffers) {
  35844. this._vertexBuffers[kind].dispose();
  35845. }
  35846. this._vertexBuffers = {};
  35847. this._totalVertices = 0;
  35848. if (this._indexBuffer) {
  35849. this._engine._releaseBuffer(this._indexBuffer);
  35850. }
  35851. this._indexBuffer = null;
  35852. this._indices = [];
  35853. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35854. this.delayLoadingFile = null;
  35855. this._delayLoadingFunction = null;
  35856. this._delayInfo = [];
  35857. this._boundingInfo = null;
  35858. this._scene.removeGeometry(this);
  35859. this._isDisposed = true;
  35860. };
  35861. /**
  35862. * Clone the current geometry into a new geometry
  35863. * @param id defines the unique ID of the new geometry
  35864. * @returns a new geometry object
  35865. */
  35866. Geometry.prototype.copy = function (id) {
  35867. var vertexData = new BABYLON.VertexData();
  35868. vertexData.indices = [];
  35869. var indices = this.getIndices();
  35870. if (indices) {
  35871. for (var index = 0; index < indices.length; index++) {
  35872. vertexData.indices.push(indices[index]);
  35873. }
  35874. }
  35875. var updatable = false;
  35876. var stopChecking = false;
  35877. var kind;
  35878. for (kind in this._vertexBuffers) {
  35879. // using slice() to make a copy of the array and not just reference it
  35880. var data = this.getVerticesData(kind);
  35881. if (data instanceof Float32Array) {
  35882. vertexData.set(new Float32Array(data), kind);
  35883. }
  35884. else {
  35885. vertexData.set(data.slice(0), kind);
  35886. }
  35887. if (!stopChecking) {
  35888. var vb = this.getVertexBuffer(kind);
  35889. if (vb) {
  35890. updatable = vb.isUpdatable();
  35891. stopChecking = !updatable;
  35892. }
  35893. }
  35894. }
  35895. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35896. geometry.delayLoadState = this.delayLoadState;
  35897. geometry.delayLoadingFile = this.delayLoadingFile;
  35898. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35899. for (kind in this._delayInfo) {
  35900. geometry._delayInfo = geometry._delayInfo || [];
  35901. geometry._delayInfo.push(kind);
  35902. }
  35903. // Bounding info
  35904. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35905. return geometry;
  35906. };
  35907. /**
  35908. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35909. * @return a JSON representation of the current geometry data (without the vertices data)
  35910. */
  35911. Geometry.prototype.serialize = function () {
  35912. var serializationObject = {};
  35913. serializationObject.id = this.id;
  35914. serializationObject.updatable = this._updatable;
  35915. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35916. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35917. }
  35918. return serializationObject;
  35919. };
  35920. Geometry.prototype.toNumberArray = function (origin) {
  35921. if (Array.isArray(origin)) {
  35922. return origin;
  35923. }
  35924. else {
  35925. return Array.prototype.slice.call(origin);
  35926. }
  35927. };
  35928. /**
  35929. * Serialize all vertices data into a JSON oject
  35930. * @returns a JSON representation of the current geometry data
  35931. */
  35932. Geometry.prototype.serializeVerticeData = function () {
  35933. var serializationObject = this.serialize();
  35934. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35935. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35936. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35937. serializationObject.positions._updatable = true;
  35938. }
  35939. }
  35940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35941. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35942. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35943. serializationObject.normals._updatable = true;
  35944. }
  35945. }
  35946. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35947. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35948. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35949. serializationObject.tangets._updatable = true;
  35950. }
  35951. }
  35952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35953. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35954. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35955. serializationObject.uvs._updatable = true;
  35956. }
  35957. }
  35958. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35959. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35960. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35961. serializationObject.uv2s._updatable = true;
  35962. }
  35963. }
  35964. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35965. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35966. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35967. serializationObject.uv3s._updatable = true;
  35968. }
  35969. }
  35970. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35971. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35972. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35973. serializationObject.uv4s._updatable = true;
  35974. }
  35975. }
  35976. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35977. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35978. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35979. serializationObject.uv5s._updatable = true;
  35980. }
  35981. }
  35982. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35983. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35984. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35985. serializationObject.uv6s._updatable = true;
  35986. }
  35987. }
  35988. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35989. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35990. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35991. serializationObject.colors._updatable = true;
  35992. }
  35993. }
  35994. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35995. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35996. serializationObject.matricesIndices._isExpanded = true;
  35997. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35998. serializationObject.matricesIndices._updatable = true;
  35999. }
  36000. }
  36001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36002. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  36003. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36004. serializationObject.matricesWeights._updatable = true;
  36005. }
  36006. }
  36007. serializationObject.indices = this.toNumberArray(this.getIndices());
  36008. return serializationObject;
  36009. };
  36010. // Statics
  36011. /**
  36012. * Extracts a clone of a mesh geometry
  36013. * @param mesh defines the source mesh
  36014. * @param id defines the unique ID of the new geometry object
  36015. * @returns the new geometry object
  36016. */
  36017. Geometry.ExtractFromMesh = function (mesh, id) {
  36018. var geometry = mesh._geometry;
  36019. if (!geometry) {
  36020. return null;
  36021. }
  36022. return geometry.copy(id);
  36023. };
  36024. /**
  36025. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36026. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36027. * Be aware Math.random() could cause collisions, but:
  36028. * "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"
  36029. * @returns a string containing a new GUID
  36030. */
  36031. Geometry.RandomId = function () {
  36032. return BABYLON.Tools.RandomId();
  36033. };
  36034. /** @ignore */
  36035. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36036. var scene = mesh.getScene();
  36037. // Geometry
  36038. var geometryId = parsedGeometry.geometryId;
  36039. if (geometryId) {
  36040. var geometry = scene.getGeometryByID(geometryId);
  36041. if (geometry) {
  36042. geometry.applyToMesh(mesh);
  36043. }
  36044. }
  36045. else if (parsedGeometry instanceof ArrayBuffer) {
  36046. var binaryInfo = mesh._binaryInfo;
  36047. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36048. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36049. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36050. }
  36051. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36052. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36053. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36054. }
  36055. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36056. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36057. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36058. }
  36059. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36060. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36061. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36062. }
  36063. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36064. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36065. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36066. }
  36067. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36068. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36069. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36070. }
  36071. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36072. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36073. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36074. }
  36075. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36076. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36077. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36078. }
  36079. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36080. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36081. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36082. }
  36083. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36084. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36085. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36086. }
  36087. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36088. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36089. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36090. }
  36091. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36092. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36093. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36094. }
  36095. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36096. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36097. mesh.setIndices(indicesData, null);
  36098. }
  36099. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36100. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36101. mesh.subMeshes = [];
  36102. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36103. var materialIndex = subMeshesData[(i * 5) + 0];
  36104. var verticesStart = subMeshesData[(i * 5) + 1];
  36105. var verticesCount = subMeshesData[(i * 5) + 2];
  36106. var indexStart = subMeshesData[(i * 5) + 3];
  36107. var indexCount = subMeshesData[(i * 5) + 4];
  36108. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36109. }
  36110. }
  36111. }
  36112. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36113. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36114. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36115. if (parsedGeometry.tangents) {
  36116. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36117. }
  36118. if (parsedGeometry.uvs) {
  36119. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36120. }
  36121. if (parsedGeometry.uvs2) {
  36122. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36123. }
  36124. if (parsedGeometry.uvs3) {
  36125. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36126. }
  36127. if (parsedGeometry.uvs4) {
  36128. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36129. }
  36130. if (parsedGeometry.uvs5) {
  36131. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36132. }
  36133. if (parsedGeometry.uvs6) {
  36134. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36135. }
  36136. if (parsedGeometry.colors) {
  36137. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36138. }
  36139. if (parsedGeometry.matricesIndices) {
  36140. if (!parsedGeometry.matricesIndices._isExpanded) {
  36141. var floatIndices = [];
  36142. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36143. var matricesIndex = parsedGeometry.matricesIndices[i];
  36144. floatIndices.push(matricesIndex & 0x000000FF);
  36145. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36146. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36147. floatIndices.push(matricesIndex >> 24);
  36148. }
  36149. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36150. }
  36151. else {
  36152. delete parsedGeometry.matricesIndices._isExpanded;
  36153. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36154. }
  36155. }
  36156. if (parsedGeometry.matricesIndicesExtra) {
  36157. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36158. var floatIndices = [];
  36159. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36160. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36161. floatIndices.push(matricesIndex & 0x000000FF);
  36162. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36163. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36164. floatIndices.push(matricesIndex >> 24);
  36165. }
  36166. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36167. }
  36168. else {
  36169. delete parsedGeometry.matricesIndices._isExpanded;
  36170. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36171. }
  36172. }
  36173. if (parsedGeometry.matricesWeights) {
  36174. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36175. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36176. }
  36177. if (parsedGeometry.matricesWeightsExtra) {
  36178. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36179. }
  36180. mesh.setIndices(parsedGeometry.indices, null);
  36181. }
  36182. // SubMeshes
  36183. if (parsedGeometry.subMeshes) {
  36184. mesh.subMeshes = [];
  36185. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36186. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36187. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36188. }
  36189. }
  36190. // Flat shading
  36191. if (mesh._shouldGenerateFlatShading) {
  36192. mesh.convertToFlatShadedMesh();
  36193. delete mesh._shouldGenerateFlatShading;
  36194. }
  36195. // Update
  36196. mesh.computeWorldMatrix(true);
  36197. // Octree
  36198. var sceneOctree = scene.selectionOctree;
  36199. if (sceneOctree !== undefined && sceneOctree !== null) {
  36200. sceneOctree.addMesh(mesh);
  36201. }
  36202. };
  36203. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36204. var epsilon = 1e-3;
  36205. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36206. return;
  36207. }
  36208. var noInfluenceBoneIndex = 0.0;
  36209. if (parsedGeometry.skeletonId > -1) {
  36210. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36211. if (!skeleton) {
  36212. return;
  36213. }
  36214. noInfluenceBoneIndex = skeleton.bones.length;
  36215. }
  36216. else {
  36217. return;
  36218. }
  36219. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36220. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36221. var matricesWeights = parsedGeometry.matricesWeights;
  36222. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36223. var influencers = parsedGeometry.numBoneInfluencer;
  36224. var size = matricesWeights.length;
  36225. for (var i = 0; i < size; i += 4) {
  36226. var weight = 0.0;
  36227. var firstZeroWeight = -1;
  36228. for (var j = 0; j < 4; j++) {
  36229. var w = matricesWeights[i + j];
  36230. weight += w;
  36231. if (w < epsilon && firstZeroWeight < 0) {
  36232. firstZeroWeight = j;
  36233. }
  36234. }
  36235. if (matricesWeightsExtra) {
  36236. for (var j = 0; j < 4; j++) {
  36237. var w = matricesWeightsExtra[i + j];
  36238. weight += w;
  36239. if (w < epsilon && firstZeroWeight < 0) {
  36240. firstZeroWeight = j + 4;
  36241. }
  36242. }
  36243. }
  36244. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36245. firstZeroWeight = influencers - 1;
  36246. }
  36247. if (weight > epsilon) {
  36248. var mweight = 1.0 / weight;
  36249. for (var j = 0; j < 4; j++) {
  36250. matricesWeights[i + j] *= mweight;
  36251. }
  36252. if (matricesWeightsExtra) {
  36253. for (var j = 0; j < 4; j++) {
  36254. matricesWeightsExtra[i + j] *= mweight;
  36255. }
  36256. }
  36257. }
  36258. else {
  36259. if (firstZeroWeight >= 4) {
  36260. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36261. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36262. }
  36263. else {
  36264. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36265. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36266. }
  36267. }
  36268. }
  36269. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36270. if (parsedGeometry.matricesWeightsExtra) {
  36271. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36272. }
  36273. };
  36274. /**
  36275. * Create a new geometry from persisted data (Using .babylon file format)
  36276. * @param parsedVertexData defines the persisted data
  36277. * @param scene defines the hosting scene
  36278. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36279. * @returns the new geometry object
  36280. */
  36281. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36282. if (scene.getGeometryByID(parsedVertexData.id)) {
  36283. return null; // null since geometry could be something else than a box...
  36284. }
  36285. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36286. if (BABYLON.Tags) {
  36287. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36288. }
  36289. if (parsedVertexData.delayLoadingFile) {
  36290. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36291. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36292. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36293. geometry._delayInfo = [];
  36294. if (parsedVertexData.hasUVs) {
  36295. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36296. }
  36297. if (parsedVertexData.hasUVs2) {
  36298. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36299. }
  36300. if (parsedVertexData.hasUVs3) {
  36301. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36302. }
  36303. if (parsedVertexData.hasUVs4) {
  36304. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36305. }
  36306. if (parsedVertexData.hasUVs5) {
  36307. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36308. }
  36309. if (parsedVertexData.hasUVs6) {
  36310. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36311. }
  36312. if (parsedVertexData.hasColors) {
  36313. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36314. }
  36315. if (parsedVertexData.hasMatricesIndices) {
  36316. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36317. }
  36318. if (parsedVertexData.hasMatricesWeights) {
  36319. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36320. }
  36321. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36322. }
  36323. else {
  36324. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36325. }
  36326. scene.pushGeometry(geometry, true);
  36327. return geometry;
  36328. };
  36329. return Geometry;
  36330. }());
  36331. BABYLON.Geometry = Geometry;
  36332. // Primitives
  36333. /// Abstract class
  36334. /**
  36335. * Abstract class used to provide common services for all typed geometries
  36336. */
  36337. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36338. __extends(_PrimitiveGeometry, _super);
  36339. /**
  36340. * Creates a new typed geometry
  36341. * @param id defines the unique ID of the geometry
  36342. * @param scene defines the hosting scene
  36343. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36344. * @param mesh defines the hosting mesh (can be null)
  36345. */
  36346. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36347. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36348. if (mesh === void 0) { mesh = null; }
  36349. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36350. _this._canBeRegenerated = _canBeRegenerated;
  36351. _this._beingRegenerated = true;
  36352. _this.regenerate();
  36353. _this._beingRegenerated = false;
  36354. return _this;
  36355. }
  36356. /**
  36357. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36358. * @returns true if the geometry can be regenerated
  36359. */
  36360. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36361. return this._canBeRegenerated;
  36362. };
  36363. /**
  36364. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36365. */
  36366. _PrimitiveGeometry.prototype.regenerate = function () {
  36367. if (!this._canBeRegenerated) {
  36368. return;
  36369. }
  36370. this._beingRegenerated = true;
  36371. this.setAllVerticesData(this._regenerateVertexData(), false);
  36372. this._beingRegenerated = false;
  36373. };
  36374. /**
  36375. * Clone the geometry
  36376. * @param id defines the unique ID of the new geometry
  36377. * @returns the new geometry
  36378. */
  36379. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36380. return _super.prototype.copy.call(this, id);
  36381. };
  36382. // overrides
  36383. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36384. if (!this._beingRegenerated) {
  36385. return;
  36386. }
  36387. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36388. };
  36389. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36390. if (!this._beingRegenerated) {
  36391. return;
  36392. }
  36393. _super.prototype.setVerticesData.call(this, kind, data, false);
  36394. };
  36395. // to override
  36396. /** @ignore */
  36397. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36398. throw new Error("Abstract method");
  36399. };
  36400. _PrimitiveGeometry.prototype.copy = function (id) {
  36401. throw new Error("Must be overriden in sub-classes.");
  36402. };
  36403. _PrimitiveGeometry.prototype.serialize = function () {
  36404. var serializationObject = _super.prototype.serialize.call(this);
  36405. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36406. return serializationObject;
  36407. };
  36408. return _PrimitiveGeometry;
  36409. }(Geometry));
  36410. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36411. /**
  36412. * Creates a ribbon geometry
  36413. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36414. */
  36415. var RibbonGeometry = /** @class */ (function (_super) {
  36416. __extends(RibbonGeometry, _super);
  36417. /**
  36418. * Creates a ribbon geometry
  36419. * @param id defines the unique ID of the geometry
  36420. * @param scene defines the hosting scene
  36421. * @param pathArray defines the array of paths to use
  36422. * @param closeArray defines if the last path and the first path must be joined
  36423. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36424. * @param offset defines the offset between points
  36425. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36426. * @param mesh defines the hosting mesh (can be null)
  36427. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36428. */
  36429. function RibbonGeometry(id, scene,
  36430. /**
  36431. * Defines the array of paths to use
  36432. */
  36433. pathArray,
  36434. /**
  36435. * Defines if the last and first points of each path in your pathArray must be joined
  36436. */
  36437. closeArray,
  36438. /**
  36439. * Defines if the last and first points of each path in your pathArray must be joined
  36440. */
  36441. closePath,
  36442. /**
  36443. * Defines the offset between points
  36444. */
  36445. offset, canBeRegenerated, mesh,
  36446. /**
  36447. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36448. */
  36449. side) {
  36450. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36451. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36452. _this.pathArray = pathArray;
  36453. _this.closeArray = closeArray;
  36454. _this.closePath = closePath;
  36455. _this.offset = offset;
  36456. _this.side = side;
  36457. return _this;
  36458. }
  36459. /** @ignore */
  36460. RibbonGeometry.prototype._regenerateVertexData = function () {
  36461. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36462. };
  36463. RibbonGeometry.prototype.copy = function (id) {
  36464. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36465. };
  36466. return RibbonGeometry;
  36467. }(_PrimitiveGeometry));
  36468. BABYLON.RibbonGeometry = RibbonGeometry;
  36469. /**
  36470. * Creates a box geometry
  36471. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36472. */
  36473. var BoxGeometry = /** @class */ (function (_super) {
  36474. __extends(BoxGeometry, _super);
  36475. /**
  36476. * Creates a box geometry
  36477. * @param id defines the unique ID of the geometry
  36478. * @param scene defines the hosting scene
  36479. * @param size defines the zise of the box (width, height and depth are the same)
  36480. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36481. * @param mesh defines the hosting mesh (can be null)
  36482. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36483. */
  36484. function BoxGeometry(id, scene,
  36485. /**
  36486. * Defines the zise of the box (width, height and depth are the same)
  36487. */
  36488. size, canBeRegenerated, mesh,
  36489. /**
  36490. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36491. */
  36492. side) {
  36493. if (mesh === void 0) { mesh = null; }
  36494. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36495. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36496. _this.size = size;
  36497. _this.side = side;
  36498. return _this;
  36499. }
  36500. BoxGeometry.prototype._regenerateVertexData = function () {
  36501. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36502. };
  36503. BoxGeometry.prototype.copy = function (id) {
  36504. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36505. };
  36506. BoxGeometry.prototype.serialize = function () {
  36507. var serializationObject = _super.prototype.serialize.call(this);
  36508. serializationObject.size = this.size;
  36509. return serializationObject;
  36510. };
  36511. BoxGeometry.Parse = function (parsedBox, scene) {
  36512. if (scene.getGeometryByID(parsedBox.id)) {
  36513. return null; // null since geometry could be something else than a box...
  36514. }
  36515. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36516. if (BABYLON.Tags) {
  36517. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36518. }
  36519. scene.pushGeometry(box, true);
  36520. return box;
  36521. };
  36522. return BoxGeometry;
  36523. }(_PrimitiveGeometry));
  36524. BABYLON.BoxGeometry = BoxGeometry;
  36525. /**
  36526. * Creates a sphere geometry
  36527. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36528. */
  36529. var SphereGeometry = /** @class */ (function (_super) {
  36530. __extends(SphereGeometry, _super);
  36531. /**
  36532. * Create a new sphere geometry
  36533. * @param id defines the unique ID of the geometry
  36534. * @param scene defines the hosting scene
  36535. * @param segments defines the number of segments to use to create the sphere
  36536. * @param diameter defines the diameter of the sphere
  36537. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36538. * @param mesh defines the hosting mesh (can be null)
  36539. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36540. */
  36541. function SphereGeometry(id, scene,
  36542. /**
  36543. * Defines the number of segments to use to create the sphere
  36544. */
  36545. segments,
  36546. /**
  36547. * Defines the diameter of the sphere
  36548. */
  36549. diameter, canBeRegenerated, mesh,
  36550. /**
  36551. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36552. */
  36553. side) {
  36554. if (mesh === void 0) { mesh = null; }
  36555. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36556. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36557. _this.segments = segments;
  36558. _this.diameter = diameter;
  36559. _this.side = side;
  36560. return _this;
  36561. }
  36562. SphereGeometry.prototype._regenerateVertexData = function () {
  36563. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36564. };
  36565. SphereGeometry.prototype.copy = function (id) {
  36566. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36567. };
  36568. SphereGeometry.prototype.serialize = function () {
  36569. var serializationObject = _super.prototype.serialize.call(this);
  36570. serializationObject.segments = this.segments;
  36571. serializationObject.diameter = this.diameter;
  36572. return serializationObject;
  36573. };
  36574. SphereGeometry.Parse = function (parsedSphere, scene) {
  36575. if (scene.getGeometryByID(parsedSphere.id)) {
  36576. return null; // null since geometry could be something else than a sphere...
  36577. }
  36578. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36579. if (BABYLON.Tags) {
  36580. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36581. }
  36582. scene.pushGeometry(sphere, true);
  36583. return sphere;
  36584. };
  36585. return SphereGeometry;
  36586. }(_PrimitiveGeometry));
  36587. BABYLON.SphereGeometry = SphereGeometry;
  36588. /**
  36589. * Creates a disc geometry
  36590. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36591. */
  36592. var DiscGeometry = /** @class */ (function (_super) {
  36593. __extends(DiscGeometry, _super);
  36594. /**
  36595. * Creates a new disc geometry
  36596. * @param id defines the unique ID of the geometry
  36597. * @param scene defines the hosting scene
  36598. * @param radius defines the radius of the disc
  36599. * @param tessellation defines the tesselation factor to apply to the disc
  36600. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36601. * @param mesh defines the hosting mesh (can be null)
  36602. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36603. */
  36604. function DiscGeometry(id, scene,
  36605. /**
  36606. * Defines the radius of the disc
  36607. */
  36608. radius,
  36609. /**
  36610. * Defines the tesselation factor to apply to the disc
  36611. */
  36612. tessellation, canBeRegenerated, mesh,
  36613. /**
  36614. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36615. */
  36616. side) {
  36617. if (mesh === void 0) { mesh = null; }
  36618. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36619. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36620. _this.radius = radius;
  36621. _this.tessellation = tessellation;
  36622. _this.side = side;
  36623. return _this;
  36624. }
  36625. DiscGeometry.prototype._regenerateVertexData = function () {
  36626. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36627. };
  36628. DiscGeometry.prototype.copy = function (id) {
  36629. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36630. };
  36631. return DiscGeometry;
  36632. }(_PrimitiveGeometry));
  36633. BABYLON.DiscGeometry = DiscGeometry;
  36634. /**
  36635. * Creates a new cylinder geometry
  36636. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36637. */
  36638. var CylinderGeometry = /** @class */ (function (_super) {
  36639. __extends(CylinderGeometry, _super);
  36640. /**
  36641. * Creates a new cylinder geometry
  36642. * @param id defines the unique ID of the geometry
  36643. * @param scene defines the hosting scene
  36644. * @param height defines the height of the cylinder
  36645. * @param diameterTop defines the diameter of the cylinder's top cap
  36646. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36647. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36648. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36649. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36650. * @param mesh defines the hosting mesh (can be null)
  36651. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36652. */
  36653. function CylinderGeometry(id, scene,
  36654. /**
  36655. * Defines the height of the cylinder
  36656. */
  36657. height,
  36658. /**
  36659. * Defines the diameter of the cylinder's top cap
  36660. */
  36661. diameterTop,
  36662. /**
  36663. * Defines the diameter of the cylinder's bottom cap
  36664. */
  36665. diameterBottom,
  36666. /**
  36667. * Defines the tessellation factor to apply to the cylinder
  36668. */
  36669. tessellation,
  36670. /**
  36671. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36672. */
  36673. subdivisions, canBeRegenerated, mesh,
  36674. /**
  36675. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36676. */
  36677. side) {
  36678. if (subdivisions === void 0) { subdivisions = 1; }
  36679. if (mesh === void 0) { mesh = null; }
  36680. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36681. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36682. _this.height = height;
  36683. _this.diameterTop = diameterTop;
  36684. _this.diameterBottom = diameterBottom;
  36685. _this.tessellation = tessellation;
  36686. _this.subdivisions = subdivisions;
  36687. _this.side = side;
  36688. return _this;
  36689. }
  36690. CylinderGeometry.prototype._regenerateVertexData = function () {
  36691. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36692. };
  36693. CylinderGeometry.prototype.copy = function (id) {
  36694. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36695. };
  36696. CylinderGeometry.prototype.serialize = function () {
  36697. var serializationObject = _super.prototype.serialize.call(this);
  36698. serializationObject.height = this.height;
  36699. serializationObject.diameterTop = this.diameterTop;
  36700. serializationObject.diameterBottom = this.diameterBottom;
  36701. serializationObject.tessellation = this.tessellation;
  36702. return serializationObject;
  36703. };
  36704. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36705. if (scene.getGeometryByID(parsedCylinder.id)) {
  36706. return null; // null since geometry could be something else than a cylinder...
  36707. }
  36708. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36709. if (BABYLON.Tags) {
  36710. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36711. }
  36712. scene.pushGeometry(cylinder, true);
  36713. return cylinder;
  36714. };
  36715. return CylinderGeometry;
  36716. }(_PrimitiveGeometry));
  36717. BABYLON.CylinderGeometry = CylinderGeometry;
  36718. /**
  36719. * Creates a new torus geometry
  36720. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36721. */
  36722. var TorusGeometry = /** @class */ (function (_super) {
  36723. __extends(TorusGeometry, _super);
  36724. /**
  36725. * Creates a new torus geometry
  36726. * @param id defines the unique ID of the geometry
  36727. * @param scene defines the hosting scene
  36728. * @param diameter defines the diameter of the torus
  36729. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36730. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36731. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36732. * @param mesh defines the hosting mesh (can be null)
  36733. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36734. */
  36735. function TorusGeometry(id, scene,
  36736. /**
  36737. * Defines the diameter of the torus
  36738. */
  36739. diameter,
  36740. /**
  36741. * Defines the thickness of the torus (ie. internal diameter)
  36742. */
  36743. thickness,
  36744. /**
  36745. * Defines the tesselation factor to apply to the torus
  36746. */
  36747. tessellation, canBeRegenerated, mesh,
  36748. /**
  36749. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36750. */
  36751. side) {
  36752. if (mesh === void 0) { mesh = null; }
  36753. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36754. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36755. _this.diameter = diameter;
  36756. _this.thickness = thickness;
  36757. _this.tessellation = tessellation;
  36758. _this.side = side;
  36759. return _this;
  36760. }
  36761. TorusGeometry.prototype._regenerateVertexData = function () {
  36762. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36763. };
  36764. TorusGeometry.prototype.copy = function (id) {
  36765. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36766. };
  36767. TorusGeometry.prototype.serialize = function () {
  36768. var serializationObject = _super.prototype.serialize.call(this);
  36769. serializationObject.diameter = this.diameter;
  36770. serializationObject.thickness = this.thickness;
  36771. serializationObject.tessellation = this.tessellation;
  36772. return serializationObject;
  36773. };
  36774. TorusGeometry.Parse = function (parsedTorus, scene) {
  36775. if (scene.getGeometryByID(parsedTorus.id)) {
  36776. return null; // null since geometry could be something else than a torus...
  36777. }
  36778. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36779. if (BABYLON.Tags) {
  36780. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36781. }
  36782. scene.pushGeometry(torus, true);
  36783. return torus;
  36784. };
  36785. return TorusGeometry;
  36786. }(_PrimitiveGeometry));
  36787. BABYLON.TorusGeometry = TorusGeometry;
  36788. /**
  36789. * Creates a new ground geometry
  36790. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36791. */
  36792. var GroundGeometry = /** @class */ (function (_super) {
  36793. __extends(GroundGeometry, _super);
  36794. /**
  36795. * Creates a new ground geometry
  36796. * @param id defines the unique ID of the geometry
  36797. * @param scene defines the hosting scene
  36798. * @param width defines the width of the ground
  36799. * @param height defines the height of the ground
  36800. * @param subdivisions defines the subdivisions to apply to the ground
  36801. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36802. * @param mesh defines the hosting mesh (can be null)
  36803. */
  36804. function GroundGeometry(id, scene,
  36805. /**
  36806. * Defines the width of the ground
  36807. */
  36808. width,
  36809. /**
  36810. * Defines the height of the ground
  36811. */
  36812. height,
  36813. /**
  36814. * Defines the subdivisions to apply to the ground
  36815. */
  36816. subdivisions, canBeRegenerated, mesh) {
  36817. if (mesh === void 0) { mesh = null; }
  36818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36819. _this.width = width;
  36820. _this.height = height;
  36821. _this.subdivisions = subdivisions;
  36822. return _this;
  36823. }
  36824. GroundGeometry.prototype._regenerateVertexData = function () {
  36825. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36826. };
  36827. GroundGeometry.prototype.copy = function (id) {
  36828. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36829. };
  36830. GroundGeometry.prototype.serialize = function () {
  36831. var serializationObject = _super.prototype.serialize.call(this);
  36832. serializationObject.width = this.width;
  36833. serializationObject.height = this.height;
  36834. serializationObject.subdivisions = this.subdivisions;
  36835. return serializationObject;
  36836. };
  36837. GroundGeometry.Parse = function (parsedGround, scene) {
  36838. if (scene.getGeometryByID(parsedGround.id)) {
  36839. return null; // null since geometry could be something else than a ground...
  36840. }
  36841. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36842. if (BABYLON.Tags) {
  36843. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36844. }
  36845. scene.pushGeometry(ground, true);
  36846. return ground;
  36847. };
  36848. return GroundGeometry;
  36849. }(_PrimitiveGeometry));
  36850. BABYLON.GroundGeometry = GroundGeometry;
  36851. /**
  36852. * Creates a tiled ground geometry
  36853. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36854. */
  36855. var TiledGroundGeometry = /** @class */ (function (_super) {
  36856. __extends(TiledGroundGeometry, _super);
  36857. /**
  36858. * Creates a tiled ground geometry
  36859. * @param id defines the unique ID of the geometry
  36860. * @param scene defines the hosting scene
  36861. * @param xmin defines the minimum value on X axis
  36862. * @param zmin defines the minimum value on Z axis
  36863. * @param xmax defines the maximum value on X axis
  36864. * @param zmax defines the maximum value on Z axis
  36865. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36866. * @param precision defines the precision to use when computing the tiles
  36867. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36868. * @param mesh defines the hosting mesh (can be null)
  36869. */
  36870. function TiledGroundGeometry(id, scene,
  36871. /**
  36872. * Defines the minimum value on X axis
  36873. */
  36874. xmin,
  36875. /**
  36876. * Defines the minimum value on Z axis
  36877. */
  36878. zmin,
  36879. /**
  36880. * Defines the maximum value on X axis
  36881. */
  36882. xmax,
  36883. /**
  36884. * Defines the maximum value on Z axis
  36885. */
  36886. zmax,
  36887. /**
  36888. * Defines the subdivisions to apply to the ground
  36889. */
  36890. subdivisions,
  36891. /**
  36892. * Defines the precision to use when computing the tiles
  36893. */
  36894. precision, canBeRegenerated, mesh) {
  36895. if (mesh === void 0) { mesh = null; }
  36896. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36897. _this.xmin = xmin;
  36898. _this.zmin = zmin;
  36899. _this.xmax = xmax;
  36900. _this.zmax = zmax;
  36901. _this.subdivisions = subdivisions;
  36902. _this.precision = precision;
  36903. return _this;
  36904. }
  36905. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36906. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36907. };
  36908. TiledGroundGeometry.prototype.copy = function (id) {
  36909. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36910. };
  36911. return TiledGroundGeometry;
  36912. }(_PrimitiveGeometry));
  36913. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36914. /**
  36915. * Creates a plane geometry
  36916. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36917. */
  36918. var PlaneGeometry = /** @class */ (function (_super) {
  36919. __extends(PlaneGeometry, _super);
  36920. /**
  36921. * Creates a plane geometry
  36922. * @param id defines the unique ID of the geometry
  36923. * @param scene defines the hosting scene
  36924. * @param size defines the size of the plane (width === height)
  36925. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36926. * @param mesh defines the hosting mesh (can be null)
  36927. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36928. */
  36929. function PlaneGeometry(id, scene,
  36930. /**
  36931. * Defines the size of the plane (width === height)
  36932. */
  36933. size, canBeRegenerated, mesh,
  36934. /**
  36935. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36936. */
  36937. side) {
  36938. if (mesh === void 0) { mesh = null; }
  36939. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36940. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36941. _this.size = size;
  36942. _this.side = side;
  36943. return _this;
  36944. }
  36945. PlaneGeometry.prototype._regenerateVertexData = function () {
  36946. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36947. };
  36948. PlaneGeometry.prototype.copy = function (id) {
  36949. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36950. };
  36951. PlaneGeometry.prototype.serialize = function () {
  36952. var serializationObject = _super.prototype.serialize.call(this);
  36953. serializationObject.size = this.size;
  36954. return serializationObject;
  36955. };
  36956. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36957. if (scene.getGeometryByID(parsedPlane.id)) {
  36958. return null; // null since geometry could be something else than a ground...
  36959. }
  36960. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36961. if (BABYLON.Tags) {
  36962. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36963. }
  36964. scene.pushGeometry(plane, true);
  36965. return plane;
  36966. };
  36967. return PlaneGeometry;
  36968. }(_PrimitiveGeometry));
  36969. BABYLON.PlaneGeometry = PlaneGeometry;
  36970. /**
  36971. * Creates a torus knot geometry
  36972. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36973. */
  36974. var TorusKnotGeometry = /** @class */ (function (_super) {
  36975. __extends(TorusKnotGeometry, _super);
  36976. /**
  36977. * Creates a torus knot geometry
  36978. * @param id defines the unique ID of the geometry
  36979. * @param scene defines the hosting scene
  36980. * @param radius defines the radius of the torus knot
  36981. * @param tube defines the thickness of the torus knot tube
  36982. * @param radialSegments defines the number of radial segments
  36983. * @param tubularSegments defines the number of tubular segments
  36984. * @param p defines the first number of windings
  36985. * @param q defines the second number of windings
  36986. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36987. * @param mesh defines the hosting mesh (can be null)
  36988. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36989. */
  36990. function TorusKnotGeometry(id, scene,
  36991. /**
  36992. * Defines the radius of the torus knot
  36993. */
  36994. radius,
  36995. /**
  36996. * Defines the thickness of the torus knot tube
  36997. */
  36998. tube,
  36999. /**
  37000. * Defines the number of radial segments
  37001. */
  37002. radialSegments,
  37003. /**
  37004. * Defines the number of tubular segments
  37005. */
  37006. tubularSegments,
  37007. /**
  37008. * Defines the first number of windings
  37009. */
  37010. p,
  37011. /**
  37012. * Defines the second number of windings
  37013. */
  37014. q, canBeRegenerated, mesh,
  37015. /**
  37016. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  37017. */
  37018. side) {
  37019. if (mesh === void 0) { mesh = null; }
  37020. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37021. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37022. _this.radius = radius;
  37023. _this.tube = tube;
  37024. _this.radialSegments = radialSegments;
  37025. _this.tubularSegments = tubularSegments;
  37026. _this.p = p;
  37027. _this.q = q;
  37028. _this.side = side;
  37029. return _this;
  37030. }
  37031. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  37032. 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 });
  37033. };
  37034. TorusKnotGeometry.prototype.copy = function (id) {
  37035. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37036. };
  37037. TorusKnotGeometry.prototype.serialize = function () {
  37038. var serializationObject = _super.prototype.serialize.call(this);
  37039. serializationObject.radius = this.radius;
  37040. serializationObject.tube = this.tube;
  37041. serializationObject.radialSegments = this.radialSegments;
  37042. serializationObject.tubularSegments = this.tubularSegments;
  37043. serializationObject.p = this.p;
  37044. serializationObject.q = this.q;
  37045. return serializationObject;
  37046. };
  37047. ;
  37048. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37049. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37050. return null; // null since geometry could be something else than a ground...
  37051. }
  37052. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37053. if (BABYLON.Tags) {
  37054. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37055. }
  37056. scene.pushGeometry(torusKnot, true);
  37057. return torusKnot;
  37058. };
  37059. return TorusKnotGeometry;
  37060. }(_PrimitiveGeometry));
  37061. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37062. //}
  37063. })(BABYLON || (BABYLON = {}));
  37064. //# sourceMappingURL=babylon.geometry.js.map
  37065. "use strict";
  37066. var BABYLON;
  37067. (function (BABYLON) {
  37068. /**
  37069. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37070. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37071. */
  37072. var PostProcessManager = /** @class */ (function () {
  37073. /**
  37074. * Creates a new instance PostProcess
  37075. * @param scene The scene that the post process is associated with.
  37076. */
  37077. function PostProcessManager(scene) {
  37078. this._vertexBuffers = {};
  37079. this._scene = scene;
  37080. }
  37081. PostProcessManager.prototype._prepareBuffers = function () {
  37082. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37083. return;
  37084. }
  37085. // VBO
  37086. var vertices = [];
  37087. vertices.push(1, 1);
  37088. vertices.push(-1, 1);
  37089. vertices.push(-1, -1);
  37090. vertices.push(1, -1);
  37091. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37092. this._buildIndexBuffer();
  37093. };
  37094. PostProcessManager.prototype._buildIndexBuffer = function () {
  37095. // Indices
  37096. var indices = [];
  37097. indices.push(0);
  37098. indices.push(1);
  37099. indices.push(2);
  37100. indices.push(0);
  37101. indices.push(2);
  37102. indices.push(3);
  37103. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37104. };
  37105. /**
  37106. * Rebuilds the vertex buffers of the manager.
  37107. */
  37108. PostProcessManager.prototype._rebuild = function () {
  37109. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37110. if (!vb) {
  37111. return;
  37112. }
  37113. vb._rebuild();
  37114. this._buildIndexBuffer();
  37115. };
  37116. // Methods
  37117. /**
  37118. * Prepares a frame to be run through a post process.
  37119. * @param sourceTexture The input texture to the post procesess. (default: null)
  37120. * @param postProcesses An array of post processes to be run. (default: null)
  37121. * @returns True if the post processes were able to be run.
  37122. */
  37123. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37124. if (sourceTexture === void 0) { sourceTexture = null; }
  37125. if (postProcesses === void 0) { postProcesses = null; }
  37126. var camera = this._scene.activeCamera;
  37127. if (!camera) {
  37128. return false;
  37129. }
  37130. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37131. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37132. return false;
  37133. }
  37134. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37135. return true;
  37136. };
  37137. /**
  37138. * Manually render a set of post processes to a texture.
  37139. * @param postProcesses An array of post processes to be run.
  37140. * @param targetTexture The target texture to render to.
  37141. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37142. */
  37143. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37144. if (targetTexture === void 0) { targetTexture = null; }
  37145. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37146. var engine = this._scene.getEngine();
  37147. for (var index = 0; index < postProcesses.length; index++) {
  37148. if (index < postProcesses.length - 1) {
  37149. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37150. }
  37151. else {
  37152. if (targetTexture) {
  37153. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37154. }
  37155. else {
  37156. engine.restoreDefaultFramebuffer();
  37157. }
  37158. }
  37159. var pp = postProcesses[index];
  37160. var effect = pp.apply();
  37161. if (effect) {
  37162. pp.onBeforeRenderObservable.notifyObservers(effect);
  37163. // VBOs
  37164. this._prepareBuffers();
  37165. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37166. // Draw order
  37167. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37168. pp.onAfterRenderObservable.notifyObservers(effect);
  37169. }
  37170. }
  37171. // Restore depth buffer
  37172. engine.setDepthBuffer(true);
  37173. engine.setDepthWrite(true);
  37174. };
  37175. /**
  37176. * Finalize the result of the output of the postprocesses.
  37177. * @param doNotPresent If true the result will not be displayed to the screen.
  37178. * @param targetTexture The target texture to render to.
  37179. * @param faceIndex The index of the face to bind the target texture to.
  37180. * @param postProcesses The array of post processes to render.
  37181. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37182. */
  37183. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37184. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37185. var camera = this._scene.activeCamera;
  37186. if (!camera) {
  37187. return;
  37188. }
  37189. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37190. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37191. return;
  37192. }
  37193. var engine = this._scene.getEngine();
  37194. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37195. var pp = postProcesses[index];
  37196. if (index < len - 1) {
  37197. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37198. }
  37199. else {
  37200. if (targetTexture) {
  37201. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37202. }
  37203. else {
  37204. engine.restoreDefaultFramebuffer();
  37205. }
  37206. }
  37207. if (doNotPresent) {
  37208. break;
  37209. }
  37210. var effect = pp.apply();
  37211. if (effect) {
  37212. pp.onBeforeRenderObservable.notifyObservers(effect);
  37213. // VBOs
  37214. this._prepareBuffers();
  37215. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37216. // Draw order
  37217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37218. pp.onAfterRenderObservable.notifyObservers(effect);
  37219. }
  37220. }
  37221. // Restore states
  37222. engine.setDepthBuffer(true);
  37223. engine.setDepthWrite(true);
  37224. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37225. };
  37226. /**
  37227. * Disposes of the post process manager.
  37228. */
  37229. PostProcessManager.prototype.dispose = function () {
  37230. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37231. if (buffer) {
  37232. buffer.dispose();
  37233. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37234. }
  37235. if (this._indexBuffer) {
  37236. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37237. this._indexBuffer = null;
  37238. }
  37239. };
  37240. return PostProcessManager;
  37241. }());
  37242. BABYLON.PostProcessManager = PostProcessManager;
  37243. })(BABYLON || (BABYLON = {}));
  37244. //# sourceMappingURL=babylon.postProcessManager.js.map
  37245. "use strict";
  37246. var BABYLON;
  37247. (function (BABYLON) {
  37248. /**
  37249. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37250. */
  37251. var PerformanceMonitor = /** @class */ (function () {
  37252. /**
  37253. * constructor
  37254. * @param frameSampleSize The number of samples required to saturate the sliding window
  37255. */
  37256. function PerformanceMonitor(frameSampleSize) {
  37257. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37258. this._enabled = true;
  37259. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37260. }
  37261. /**
  37262. * Samples current frame
  37263. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37264. */
  37265. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37266. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37267. if (!this._enabled)
  37268. return;
  37269. if (this._lastFrameTimeMs != null) {
  37270. var dt = timeMs - this._lastFrameTimeMs;
  37271. this._rollingFrameTime.add(dt);
  37272. }
  37273. this._lastFrameTimeMs = timeMs;
  37274. };
  37275. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37276. /**
  37277. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37278. * @return Average frame time in milliseconds
  37279. */
  37280. get: function () {
  37281. return this._rollingFrameTime.average;
  37282. },
  37283. enumerable: true,
  37284. configurable: true
  37285. });
  37286. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37287. /**
  37288. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37289. * @return Frame time variance in milliseconds squared
  37290. */
  37291. get: function () {
  37292. return this._rollingFrameTime.variance;
  37293. },
  37294. enumerable: true,
  37295. configurable: true
  37296. });
  37297. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37298. /**
  37299. * Returns the frame time of the most recent frame
  37300. * @return Frame time in milliseconds
  37301. */
  37302. get: function () {
  37303. return this._rollingFrameTime.history(0);
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37309. /**
  37310. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37311. * @return Framerate in frames per second
  37312. */
  37313. get: function () {
  37314. return 1000.0 / this._rollingFrameTime.average;
  37315. },
  37316. enumerable: true,
  37317. configurable: true
  37318. });
  37319. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37320. /**
  37321. * Returns the average framerate in frames per second using the most recent frame time
  37322. * @return Framerate in frames per second
  37323. */
  37324. get: function () {
  37325. var history = this._rollingFrameTime.history(0);
  37326. if (history === 0) {
  37327. return 0;
  37328. }
  37329. return 1000.0 / history;
  37330. },
  37331. enumerable: true,
  37332. configurable: true
  37333. });
  37334. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37335. /**
  37336. * Returns true if enough samples have been taken to completely fill the sliding window
  37337. * @return true if saturated
  37338. */
  37339. get: function () {
  37340. return this._rollingFrameTime.isSaturated();
  37341. },
  37342. enumerable: true,
  37343. configurable: true
  37344. });
  37345. /**
  37346. * Enables contributions to the sliding window sample set
  37347. */
  37348. PerformanceMonitor.prototype.enable = function () {
  37349. this._enabled = true;
  37350. };
  37351. /**
  37352. * Disables contributions to the sliding window sample set
  37353. * Samples will not be interpolated over the disabled period
  37354. */
  37355. PerformanceMonitor.prototype.disable = function () {
  37356. this._enabled = false;
  37357. //clear last sample to avoid interpolating over the disabled period when next enabled
  37358. this._lastFrameTimeMs = null;
  37359. };
  37360. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37361. /**
  37362. * Returns true if sampling is enabled
  37363. * @return true if enabled
  37364. */
  37365. get: function () {
  37366. return this._enabled;
  37367. },
  37368. enumerable: true,
  37369. configurable: true
  37370. });
  37371. /**
  37372. * Resets performance monitor
  37373. */
  37374. PerformanceMonitor.prototype.reset = function () {
  37375. //clear last sample to avoid interpolating over the disabled period when next enabled
  37376. this._lastFrameTimeMs = null;
  37377. //wipe record
  37378. this._rollingFrameTime.reset();
  37379. };
  37380. return PerformanceMonitor;
  37381. }());
  37382. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37383. /**
  37384. * RollingAverage
  37385. *
  37386. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37387. */
  37388. var RollingAverage = /** @class */ (function () {
  37389. /**
  37390. * constructor
  37391. * @param length The number of samples required to saturate the sliding window
  37392. */
  37393. function RollingAverage(length) {
  37394. this._samples = new Array(length);
  37395. this.reset();
  37396. }
  37397. /**
  37398. * Adds a sample to the sample set
  37399. * @param v The sample value
  37400. */
  37401. RollingAverage.prototype.add = function (v) {
  37402. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37403. var delta;
  37404. //we need to check if we've already wrapped round
  37405. if (this.isSaturated()) {
  37406. //remove bottom of stack from mean
  37407. var bottomValue = this._samples[this._pos];
  37408. delta = bottomValue - this.average;
  37409. this.average -= delta / (this._sampleCount - 1);
  37410. this._m2 -= delta * (bottomValue - this.average);
  37411. }
  37412. else {
  37413. this._sampleCount++;
  37414. }
  37415. //add new value to mean
  37416. delta = v - this.average;
  37417. this.average += delta / (this._sampleCount);
  37418. this._m2 += delta * (v - this.average);
  37419. //set the new variance
  37420. this.variance = this._m2 / (this._sampleCount - 1);
  37421. this._samples[this._pos] = v;
  37422. this._pos++;
  37423. this._pos %= this._samples.length; //positive wrap around
  37424. };
  37425. /**
  37426. * Returns previously added values or null if outside of history or outside the sliding window domain
  37427. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37428. * @return Value previously recorded with add() or null if outside of range
  37429. */
  37430. RollingAverage.prototype.history = function (i) {
  37431. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37432. return 0;
  37433. }
  37434. var i0 = this._wrapPosition(this._pos - 1.0);
  37435. return this._samples[this._wrapPosition(i0 - i)];
  37436. };
  37437. /**
  37438. * Returns true if enough samples have been taken to completely fill the sliding window
  37439. * @return true if sample-set saturated
  37440. */
  37441. RollingAverage.prototype.isSaturated = function () {
  37442. return this._sampleCount >= this._samples.length;
  37443. };
  37444. /**
  37445. * Resets the rolling average (equivalent to 0 samples taken so far)
  37446. */
  37447. RollingAverage.prototype.reset = function () {
  37448. this.average = 0;
  37449. this.variance = 0;
  37450. this._sampleCount = 0;
  37451. this._pos = 0;
  37452. this._m2 = 0;
  37453. };
  37454. /**
  37455. * Wraps a value around the sample range boundaries
  37456. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37457. * @return Wrapped position in sample range
  37458. */
  37459. RollingAverage.prototype._wrapPosition = function (i) {
  37460. var max = this._samples.length;
  37461. return ((i % max) + max) % max;
  37462. };
  37463. return RollingAverage;
  37464. }());
  37465. BABYLON.RollingAverage = RollingAverage;
  37466. })(BABYLON || (BABYLON = {}));
  37467. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37468. "use strict";
  37469. var BABYLON;
  37470. (function (BABYLON) {
  37471. /**
  37472. * This groups together the common properties used for image processing either in direct forward pass
  37473. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37474. * or not.
  37475. */
  37476. var ImageProcessingConfiguration = /** @class */ (function () {
  37477. function ImageProcessingConfiguration() {
  37478. /**
  37479. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37480. */
  37481. this.colorCurves = new BABYLON.ColorCurves();
  37482. this._colorCurvesEnabled = false;
  37483. this._colorGradingEnabled = false;
  37484. this._colorGradingWithGreenDepth = true;
  37485. this._colorGradingBGR = true;
  37486. this._exposure = 1.0;
  37487. this._toneMappingEnabled = false;
  37488. this._contrast = 1.0;
  37489. /**
  37490. * Vignette stretch size.
  37491. */
  37492. this.vignetteStretch = 0;
  37493. /**
  37494. * Vignette centre X Offset.
  37495. */
  37496. this.vignetteCentreX = 0;
  37497. /**
  37498. * Vignette centre Y Offset.
  37499. */
  37500. this.vignetteCentreY = 0;
  37501. /**
  37502. * Vignette weight or intensity of the vignette effect.
  37503. */
  37504. this.vignetteWeight = 1.5;
  37505. /**
  37506. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37507. * if vignetteEnabled is set to true.
  37508. */
  37509. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37510. /**
  37511. * Camera field of view used by the Vignette effect.
  37512. */
  37513. this.vignetteCameraFov = 0.5;
  37514. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37515. this._vignetteEnabled = false;
  37516. this._applyByPostProcess = false;
  37517. this._isEnabled = true;
  37518. /**
  37519. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37520. * @type {BABYLON.Observable}
  37521. */
  37522. this.onUpdateParameters = new BABYLON.Observable();
  37523. }
  37524. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37525. /**
  37526. * Gets wether the color curves effect is enabled.
  37527. */
  37528. get: function () {
  37529. return this._colorCurvesEnabled;
  37530. },
  37531. /**
  37532. * Sets wether the color curves effect is enabled.
  37533. */
  37534. set: function (value) {
  37535. if (this._colorCurvesEnabled === value) {
  37536. return;
  37537. }
  37538. this._colorCurvesEnabled = value;
  37539. this._updateParameters();
  37540. },
  37541. enumerable: true,
  37542. configurable: true
  37543. });
  37544. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37545. /**
  37546. * Gets wether the color grading effect is enabled.
  37547. */
  37548. get: function () {
  37549. return this._colorGradingEnabled;
  37550. },
  37551. /**
  37552. * Sets wether the color grading effect is enabled.
  37553. */
  37554. set: function (value) {
  37555. if (this._colorGradingEnabled === value) {
  37556. return;
  37557. }
  37558. this._colorGradingEnabled = value;
  37559. this._updateParameters();
  37560. },
  37561. enumerable: true,
  37562. configurable: true
  37563. });
  37564. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37565. /**
  37566. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37567. */
  37568. get: function () {
  37569. return this._colorGradingWithGreenDepth;
  37570. },
  37571. /**
  37572. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37573. */
  37574. set: function (value) {
  37575. if (this._colorGradingWithGreenDepth === value) {
  37576. return;
  37577. }
  37578. this._colorGradingWithGreenDepth = value;
  37579. this._updateParameters();
  37580. },
  37581. enumerable: true,
  37582. configurable: true
  37583. });
  37584. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37585. /**
  37586. * Gets wether the color grading texture contains BGR values.
  37587. */
  37588. get: function () {
  37589. return this._colorGradingBGR;
  37590. },
  37591. /**
  37592. * Sets wether the color grading texture contains BGR values.
  37593. */
  37594. set: function (value) {
  37595. if (this._colorGradingBGR === value) {
  37596. return;
  37597. }
  37598. this._colorGradingBGR = value;
  37599. this._updateParameters();
  37600. },
  37601. enumerable: true,
  37602. configurable: true
  37603. });
  37604. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37605. /**
  37606. * Gets the Exposure used in the effect.
  37607. */
  37608. get: function () {
  37609. return this._exposure;
  37610. },
  37611. /**
  37612. * Sets the Exposure used in the effect.
  37613. */
  37614. set: function (value) {
  37615. if (this._exposure === value) {
  37616. return;
  37617. }
  37618. this._exposure = value;
  37619. this._updateParameters();
  37620. },
  37621. enumerable: true,
  37622. configurable: true
  37623. });
  37624. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37625. /**
  37626. * Gets wether the tone mapping effect is enabled.
  37627. */
  37628. get: function () {
  37629. return this._toneMappingEnabled;
  37630. },
  37631. /**
  37632. * Sets wether the tone mapping effect is enabled.
  37633. */
  37634. set: function (value) {
  37635. if (this._toneMappingEnabled === value) {
  37636. return;
  37637. }
  37638. this._toneMappingEnabled = value;
  37639. this._updateParameters();
  37640. },
  37641. enumerable: true,
  37642. configurable: true
  37643. });
  37644. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37645. /**
  37646. * Gets the contrast used in the effect.
  37647. */
  37648. get: function () {
  37649. return this._contrast;
  37650. },
  37651. /**
  37652. * Sets the contrast used in the effect.
  37653. */
  37654. set: function (value) {
  37655. if (this._contrast === value) {
  37656. return;
  37657. }
  37658. this._contrast = value;
  37659. this._updateParameters();
  37660. },
  37661. enumerable: true,
  37662. configurable: true
  37663. });
  37664. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37665. /**
  37666. * Gets the vignette blend mode allowing different kind of effect.
  37667. */
  37668. get: function () {
  37669. return this._vignetteBlendMode;
  37670. },
  37671. /**
  37672. * Sets the vignette blend mode allowing different kind of effect.
  37673. */
  37674. set: function (value) {
  37675. if (this._vignetteBlendMode === value) {
  37676. return;
  37677. }
  37678. this._vignetteBlendMode = value;
  37679. this._updateParameters();
  37680. },
  37681. enumerable: true,
  37682. configurable: true
  37683. });
  37684. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37685. /**
  37686. * Gets wether the vignette effect is enabled.
  37687. */
  37688. get: function () {
  37689. return this._vignetteEnabled;
  37690. },
  37691. /**
  37692. * Sets wether the vignette effect is enabled.
  37693. */
  37694. set: function (value) {
  37695. if (this._vignetteEnabled === value) {
  37696. return;
  37697. }
  37698. this._vignetteEnabled = value;
  37699. this._updateParameters();
  37700. },
  37701. enumerable: true,
  37702. configurable: true
  37703. });
  37704. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37705. /**
  37706. * Gets wether the image processing is applied through a post process or not.
  37707. */
  37708. get: function () {
  37709. return this._applyByPostProcess;
  37710. },
  37711. /**
  37712. * Sets wether the image processing is applied through a post process or not.
  37713. */
  37714. set: function (value) {
  37715. if (this._applyByPostProcess === value) {
  37716. return;
  37717. }
  37718. this._applyByPostProcess = value;
  37719. this._updateParameters();
  37720. },
  37721. enumerable: true,
  37722. configurable: true
  37723. });
  37724. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37725. /**
  37726. * Gets wether the image processing is enabled or not.
  37727. */
  37728. get: function () {
  37729. return this._isEnabled;
  37730. },
  37731. /**
  37732. * Sets wether the image processing is enabled or not.
  37733. */
  37734. set: function (value) {
  37735. if (this._isEnabled === value) {
  37736. return;
  37737. }
  37738. this._isEnabled = value;
  37739. this._updateParameters();
  37740. },
  37741. enumerable: true,
  37742. configurable: true
  37743. });
  37744. /**
  37745. * Method called each time the image processing information changes requires to recompile the effect.
  37746. */
  37747. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37748. this.onUpdateParameters.notifyObservers(this);
  37749. };
  37750. ImageProcessingConfiguration.prototype.getClassName = function () {
  37751. return "ImageProcessingConfiguration";
  37752. };
  37753. /**
  37754. * Prepare the list of uniforms associated with the Image Processing effects.
  37755. * @param uniformsList The list of uniforms used in the effect
  37756. * @param defines the list of defines currently in use
  37757. */
  37758. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37759. if (defines.EXPOSURE) {
  37760. uniforms.push("exposureLinear");
  37761. }
  37762. if (defines.CONTRAST) {
  37763. uniforms.push("contrast");
  37764. }
  37765. if (defines.COLORGRADING) {
  37766. uniforms.push("colorTransformSettings");
  37767. }
  37768. if (defines.VIGNETTE) {
  37769. uniforms.push("vInverseScreenSize");
  37770. uniforms.push("vignetteSettings1");
  37771. uniforms.push("vignetteSettings2");
  37772. }
  37773. if (defines.COLORCURVES) {
  37774. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37775. }
  37776. };
  37777. /**
  37778. * Prepare the list of samplers associated with the Image Processing effects.
  37779. * @param uniformsList The list of uniforms used in the effect
  37780. * @param defines the list of defines currently in use
  37781. */
  37782. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37783. if (defines.COLORGRADING) {
  37784. samplersList.push("txColorTransform");
  37785. }
  37786. };
  37787. /**
  37788. * Prepare the list of defines associated to the shader.
  37789. * @param defines the list of defines to complete
  37790. */
  37791. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37792. if (forPostProcess === void 0) { forPostProcess = false; }
  37793. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37794. defines.VIGNETTE = false;
  37795. defines.TONEMAPPING = false;
  37796. defines.CONTRAST = false;
  37797. defines.EXPOSURE = false;
  37798. defines.COLORCURVES = false;
  37799. defines.COLORGRADING = false;
  37800. defines.COLORGRADING3D = false;
  37801. defines.IMAGEPROCESSING = false;
  37802. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37803. return;
  37804. }
  37805. defines.VIGNETTE = this.vignetteEnabled;
  37806. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37807. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37808. defines.TONEMAPPING = this.toneMappingEnabled;
  37809. defines.CONTRAST = (this.contrast !== 1.0);
  37810. defines.EXPOSURE = (this.exposure !== 1.0);
  37811. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37812. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37813. if (defines.COLORGRADING) {
  37814. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37815. }
  37816. else {
  37817. defines.COLORGRADING3D = false;
  37818. }
  37819. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37820. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37821. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37822. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  37823. };
  37824. /**
  37825. * Returns true if all the image processing information are ready.
  37826. */
  37827. ImageProcessingConfiguration.prototype.isReady = function () {
  37828. // Color Grading texure can not be none blocking.
  37829. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37830. };
  37831. /**
  37832. * Binds the image processing to the shader.
  37833. * @param effect The effect to bind to
  37834. */
  37835. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37836. if (aspectRatio === void 0) { aspectRatio = 1; }
  37837. // Color Curves
  37838. if (this._colorCurvesEnabled && this.colorCurves) {
  37839. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37840. }
  37841. // Vignette
  37842. if (this._vignetteEnabled) {
  37843. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37844. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37845. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37846. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37847. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37848. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37849. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37850. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37851. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37852. var vignettePower = -2.0 * this.vignetteWeight;
  37853. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37854. }
  37855. // Exposure
  37856. effect.setFloat("exposureLinear", this.exposure);
  37857. // Contrast
  37858. effect.setFloat("contrast", this.contrast);
  37859. // Color transform settings
  37860. if (this.colorGradingTexture) {
  37861. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37862. var textureSize = this.colorGradingTexture.getSize().height;
  37863. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37864. 0.5 / textureSize, // textureOffset
  37865. textureSize, // textureSize
  37866. this.colorGradingTexture.level // weight
  37867. );
  37868. }
  37869. };
  37870. /**
  37871. * Clones the current image processing instance.
  37872. * @return The cloned image processing
  37873. */
  37874. ImageProcessingConfiguration.prototype.clone = function () {
  37875. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37876. };
  37877. /**
  37878. * Serializes the current image processing instance to a json representation.
  37879. * @return a JSON representation
  37880. */
  37881. ImageProcessingConfiguration.prototype.serialize = function () {
  37882. return BABYLON.SerializationHelper.Serialize(this);
  37883. };
  37884. /**
  37885. * Parses the image processing from a json representation.
  37886. * @param source the JSON source to parse
  37887. * @return The parsed image processing
  37888. */
  37889. ImageProcessingConfiguration.Parse = function (source) {
  37890. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37891. };
  37892. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37893. /**
  37894. * Used to apply the vignette as a mix with the pixel color.
  37895. */
  37896. get: function () {
  37897. return this._VIGNETTEMODE_MULTIPLY;
  37898. },
  37899. enumerable: true,
  37900. configurable: true
  37901. });
  37902. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37903. /**
  37904. * Used to apply the vignette as a replacement of the pixel color.
  37905. */
  37906. get: function () {
  37907. return this._VIGNETTEMODE_OPAQUE;
  37908. },
  37909. enumerable: true,
  37910. configurable: true
  37911. });
  37912. // Static constants associated to the image processing.
  37913. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37914. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37915. __decorate([
  37916. BABYLON.serializeAsColorCurves()
  37917. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37918. __decorate([
  37919. BABYLON.serialize()
  37920. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37921. __decorate([
  37922. BABYLON.serializeAsTexture()
  37923. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37924. __decorate([
  37925. BABYLON.serialize()
  37926. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37927. __decorate([
  37928. BABYLON.serialize()
  37929. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37930. __decorate([
  37931. BABYLON.serialize()
  37932. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37933. __decorate([
  37934. BABYLON.serialize()
  37935. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37936. __decorate([
  37937. BABYLON.serialize()
  37938. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37939. __decorate([
  37940. BABYLON.serialize()
  37941. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37942. __decorate([
  37943. BABYLON.serialize()
  37944. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37945. __decorate([
  37946. BABYLON.serialize()
  37947. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37948. __decorate([
  37949. BABYLON.serialize()
  37950. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37951. __decorate([
  37952. BABYLON.serialize()
  37953. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37954. __decorate([
  37955. BABYLON.serializeAsColor4()
  37956. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37957. __decorate([
  37958. BABYLON.serialize()
  37959. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37960. __decorate([
  37961. BABYLON.serialize()
  37962. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37963. __decorate([
  37964. BABYLON.serialize()
  37965. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37966. __decorate([
  37967. BABYLON.serialize()
  37968. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37969. __decorate([
  37970. BABYLON.serialize()
  37971. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37972. return ImageProcessingConfiguration;
  37973. }());
  37974. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37975. })(BABYLON || (BABYLON = {}));
  37976. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37977. "use strict";
  37978. var BABYLON;
  37979. (function (BABYLON) {
  37980. /**
  37981. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37982. * It can help converting any input color in a desired output one. This can then be used to create effects
  37983. * from sepia, black and white to sixties or futuristic rendering...
  37984. *
  37985. * The only supported format is currently 3dl.
  37986. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37987. */
  37988. var ColorGradingTexture = /** @class */ (function (_super) {
  37989. __extends(ColorGradingTexture, _super);
  37990. /**
  37991. * Instantiates a ColorGradingTexture from the following parameters.
  37992. *
  37993. * @param url The location of the color gradind data (currently only supporting 3dl)
  37994. * @param scene The scene the texture will be used in
  37995. */
  37996. function ColorGradingTexture(url, scene) {
  37997. var _this = _super.call(this, scene) || this;
  37998. if (!url) {
  37999. return _this;
  38000. }
  38001. _this._engine = scene.getEngine();
  38002. _this._textureMatrix = BABYLON.Matrix.Identity();
  38003. _this.name = url;
  38004. _this.url = url;
  38005. _this.hasAlpha = false;
  38006. _this.isCube = false;
  38007. _this.is3D = _this._engine.webGLVersion > 1;
  38008. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38009. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38010. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38011. _this.anisotropicFilteringLevel = 1;
  38012. _this._texture = _this._getFromCache(url, true);
  38013. if (!_this._texture) {
  38014. if (!scene.useDelayedTextureLoading) {
  38015. _this.loadTexture();
  38016. }
  38017. else {
  38018. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38019. }
  38020. }
  38021. return _this;
  38022. }
  38023. /**
  38024. * Returns the texture matrix used in most of the material.
  38025. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38026. */
  38027. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38028. return this._textureMatrix;
  38029. };
  38030. /**
  38031. * Occurs when the file being loaded is a .3dl LUT file.
  38032. */
  38033. ColorGradingTexture.prototype.load3dlTexture = function () {
  38034. var engine = this._engine;
  38035. var texture;
  38036. if (engine.webGLVersion === 1) {
  38037. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38038. }
  38039. else {
  38040. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38041. }
  38042. this._texture = texture;
  38043. var callback = function (text) {
  38044. if (typeof text !== "string") {
  38045. return;
  38046. }
  38047. var data = null;
  38048. var tempData = null;
  38049. var line;
  38050. var lines = text.split('\n');
  38051. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38052. var maxColor = 0;
  38053. for (var i = 0; i < lines.length; i++) {
  38054. line = lines[i];
  38055. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38056. continue;
  38057. if (line.indexOf('#') === 0)
  38058. continue;
  38059. var words = line.split(" ");
  38060. if (size === 0) {
  38061. // Number of space + one
  38062. size = words.length;
  38063. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38064. tempData = new Float32Array(size * size * size * 4);
  38065. continue;
  38066. }
  38067. if (size != 0) {
  38068. var r = Math.max(parseInt(words[0]), 0);
  38069. var g = Math.max(parseInt(words[1]), 0);
  38070. var b = Math.max(parseInt(words[2]), 0);
  38071. maxColor = Math.max(r, maxColor);
  38072. maxColor = Math.max(g, maxColor);
  38073. maxColor = Math.max(b, maxColor);
  38074. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38075. if (tempData) {
  38076. tempData[pixelStorageIndex + 0] = r;
  38077. tempData[pixelStorageIndex + 1] = g;
  38078. tempData[pixelStorageIndex + 2] = b;
  38079. }
  38080. pixelIndexSlice++;
  38081. if (pixelIndexSlice % size == 0) {
  38082. pixelIndexH++;
  38083. pixelIndexSlice = 0;
  38084. if (pixelIndexH % size == 0) {
  38085. pixelIndexW++;
  38086. pixelIndexH = 0;
  38087. }
  38088. }
  38089. }
  38090. }
  38091. if (tempData && data) {
  38092. for (var i = 0; i < tempData.length; i++) {
  38093. if (i > 0 && (i + 1) % 4 === 0) {
  38094. data[i] = 255;
  38095. }
  38096. else {
  38097. var value = tempData[i];
  38098. data[i] = (value / maxColor * 255);
  38099. }
  38100. }
  38101. }
  38102. if (texture.is3D) {
  38103. texture.updateSize(size, size, size);
  38104. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38105. }
  38106. else {
  38107. texture.updateSize(size * size, size);
  38108. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38109. }
  38110. };
  38111. var scene = this.getScene();
  38112. if (scene) {
  38113. scene._loadFile(this.url, callback);
  38114. }
  38115. else {
  38116. this._engine._loadFile(this.url, callback);
  38117. }
  38118. return this._texture;
  38119. };
  38120. /**
  38121. * Starts the loading process of the texture.
  38122. */
  38123. ColorGradingTexture.prototype.loadTexture = function () {
  38124. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38125. this.load3dlTexture();
  38126. }
  38127. };
  38128. /**
  38129. * Clones the color gradind texture.
  38130. */
  38131. ColorGradingTexture.prototype.clone = function () {
  38132. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38133. // Base texture
  38134. newTexture.level = this.level;
  38135. return newTexture;
  38136. };
  38137. /**
  38138. * Called during delayed load for textures.
  38139. */
  38140. ColorGradingTexture.prototype.delayLoad = function () {
  38141. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38142. return;
  38143. }
  38144. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38145. this._texture = this._getFromCache(this.url, true);
  38146. if (!this._texture) {
  38147. this.loadTexture();
  38148. }
  38149. };
  38150. /**
  38151. * Parses a color grading texture serialized by Babylon.
  38152. * @param parsedTexture The texture information being parsedTexture
  38153. * @param scene The scene to load the texture in
  38154. * @param rootUrl The root url of the data assets to load
  38155. * @return A color gradind texture
  38156. */
  38157. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38158. var texture = null;
  38159. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38160. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38161. texture.name = parsedTexture.name;
  38162. texture.level = parsedTexture.level;
  38163. }
  38164. return texture;
  38165. };
  38166. /**
  38167. * Serializes the LUT texture to json format.
  38168. */
  38169. ColorGradingTexture.prototype.serialize = function () {
  38170. if (!this.name) {
  38171. return null;
  38172. }
  38173. var serializationObject = {};
  38174. serializationObject.name = this.name;
  38175. serializationObject.level = this.level;
  38176. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38177. return serializationObject;
  38178. };
  38179. /**
  38180. * Empty line regex stored for GC.
  38181. */
  38182. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38183. return ColorGradingTexture;
  38184. }(BABYLON.BaseTexture));
  38185. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38186. })(BABYLON || (BABYLON = {}));
  38187. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38188. "use strict";
  38189. var BABYLON;
  38190. (function (BABYLON) {
  38191. /**
  38192. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38193. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38194. * 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;
  38195. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38196. */
  38197. var ColorCurves = /** @class */ (function () {
  38198. function ColorCurves() {
  38199. this._dirty = true;
  38200. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38201. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38202. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38203. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38204. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38205. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38206. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38207. this._globalHue = 30;
  38208. this._globalDensity = 0;
  38209. this._globalSaturation = 0;
  38210. this._globalExposure = 0;
  38211. this._highlightsHue = 30;
  38212. this._highlightsDensity = 0;
  38213. this._highlightsSaturation = 0;
  38214. this._highlightsExposure = 0;
  38215. this._midtonesHue = 30;
  38216. this._midtonesDensity = 0;
  38217. this._midtonesSaturation = 0;
  38218. this._midtonesExposure = 0;
  38219. this._shadowsHue = 30;
  38220. this._shadowsDensity = 0;
  38221. this._shadowsSaturation = 0;
  38222. this._shadowsExposure = 0;
  38223. }
  38224. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38225. /**
  38226. * Gets the global Hue value.
  38227. * 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).
  38228. */
  38229. get: function () {
  38230. return this._globalHue;
  38231. },
  38232. /**
  38233. * Sets the global Hue value.
  38234. * 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).
  38235. */
  38236. set: function (value) {
  38237. this._globalHue = value;
  38238. this._dirty = true;
  38239. },
  38240. enumerable: true,
  38241. configurable: true
  38242. });
  38243. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38244. /**
  38245. * Gets the global Density value.
  38246. * 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.
  38247. * Values less than zero provide a filter of opposite hue.
  38248. */
  38249. get: function () {
  38250. return this._globalDensity;
  38251. },
  38252. /**
  38253. * Sets the global Density value.
  38254. * 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.
  38255. * Values less than zero provide a filter of opposite hue.
  38256. */
  38257. set: function (value) {
  38258. this._globalDensity = value;
  38259. this._dirty = true;
  38260. },
  38261. enumerable: true,
  38262. configurable: true
  38263. });
  38264. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38265. /**
  38266. * Gets the global Saturation value.
  38267. * 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.
  38268. */
  38269. get: function () {
  38270. return this._globalSaturation;
  38271. },
  38272. /**
  38273. * Sets the global Saturation value.
  38274. * 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.
  38275. */
  38276. set: function (value) {
  38277. this._globalSaturation = value;
  38278. this._dirty = true;
  38279. },
  38280. enumerable: true,
  38281. configurable: true
  38282. });
  38283. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38284. /**
  38285. * Gets the highlights Hue value.
  38286. * 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).
  38287. */
  38288. get: function () {
  38289. return this._highlightsHue;
  38290. },
  38291. /**
  38292. * Sets the highlights Hue value.
  38293. * 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).
  38294. */
  38295. set: function (value) {
  38296. this._highlightsHue = value;
  38297. this._dirty = true;
  38298. },
  38299. enumerable: true,
  38300. configurable: true
  38301. });
  38302. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38303. /**
  38304. * Gets the highlights Density value.
  38305. * 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.
  38306. * Values less than zero provide a filter of opposite hue.
  38307. */
  38308. get: function () {
  38309. return this._highlightsDensity;
  38310. },
  38311. /**
  38312. * Sets the highlights Density value.
  38313. * 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.
  38314. * Values less than zero provide a filter of opposite hue.
  38315. */
  38316. set: function (value) {
  38317. this._highlightsDensity = value;
  38318. this._dirty = true;
  38319. },
  38320. enumerable: true,
  38321. configurable: true
  38322. });
  38323. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38324. /**
  38325. * Gets the highlights Saturation value.
  38326. * 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.
  38327. */
  38328. get: function () {
  38329. return this._highlightsSaturation;
  38330. },
  38331. /**
  38332. * Sets the highlights Saturation value.
  38333. * 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.
  38334. */
  38335. set: function (value) {
  38336. this._highlightsSaturation = value;
  38337. this._dirty = true;
  38338. },
  38339. enumerable: true,
  38340. configurable: true
  38341. });
  38342. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38343. /**
  38344. * Gets the highlights Exposure value.
  38345. * 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.
  38346. */
  38347. get: function () {
  38348. return this._highlightsExposure;
  38349. },
  38350. /**
  38351. * Sets the highlights Exposure value.
  38352. * 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.
  38353. */
  38354. set: function (value) {
  38355. this._highlightsExposure = value;
  38356. this._dirty = true;
  38357. },
  38358. enumerable: true,
  38359. configurable: true
  38360. });
  38361. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38362. /**
  38363. * Gets the midtones Hue value.
  38364. * 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).
  38365. */
  38366. get: function () {
  38367. return this._midtonesHue;
  38368. },
  38369. /**
  38370. * Sets the midtones Hue value.
  38371. * 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).
  38372. */
  38373. set: function (value) {
  38374. this._midtonesHue = value;
  38375. this._dirty = true;
  38376. },
  38377. enumerable: true,
  38378. configurable: true
  38379. });
  38380. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38381. /**
  38382. * Gets the midtones Density value.
  38383. * 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.
  38384. * Values less than zero provide a filter of opposite hue.
  38385. */
  38386. get: function () {
  38387. return this._midtonesDensity;
  38388. },
  38389. /**
  38390. * Sets the midtones Density value.
  38391. * 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.
  38392. * Values less than zero provide a filter of opposite hue.
  38393. */
  38394. set: function (value) {
  38395. this._midtonesDensity = value;
  38396. this._dirty = true;
  38397. },
  38398. enumerable: true,
  38399. configurable: true
  38400. });
  38401. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38402. /**
  38403. * Gets the midtones Saturation value.
  38404. * 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.
  38405. */
  38406. get: function () {
  38407. return this._midtonesSaturation;
  38408. },
  38409. /**
  38410. * Sets the midtones Saturation value.
  38411. * 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.
  38412. */
  38413. set: function (value) {
  38414. this._midtonesSaturation = value;
  38415. this._dirty = true;
  38416. },
  38417. enumerable: true,
  38418. configurable: true
  38419. });
  38420. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38421. /**
  38422. * Gets the midtones Exposure value.
  38423. * 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.
  38424. */
  38425. get: function () {
  38426. return this._midtonesExposure;
  38427. },
  38428. /**
  38429. * Sets the midtones Exposure value.
  38430. * 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.
  38431. */
  38432. set: function (value) {
  38433. this._midtonesExposure = value;
  38434. this._dirty = true;
  38435. },
  38436. enumerable: true,
  38437. configurable: true
  38438. });
  38439. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38440. /**
  38441. * Gets the shadows Hue value.
  38442. * 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).
  38443. */
  38444. get: function () {
  38445. return this._shadowsHue;
  38446. },
  38447. /**
  38448. * Sets the shadows Hue value.
  38449. * 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).
  38450. */
  38451. set: function (value) {
  38452. this._shadowsHue = value;
  38453. this._dirty = true;
  38454. },
  38455. enumerable: true,
  38456. configurable: true
  38457. });
  38458. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38459. /**
  38460. * Gets the shadows Density value.
  38461. * 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.
  38462. * Values less than zero provide a filter of opposite hue.
  38463. */
  38464. get: function () {
  38465. return this._shadowsDensity;
  38466. },
  38467. /**
  38468. * Sets the shadows Density value.
  38469. * 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.
  38470. * Values less than zero provide a filter of opposite hue.
  38471. */
  38472. set: function (value) {
  38473. this._shadowsDensity = value;
  38474. this._dirty = true;
  38475. },
  38476. enumerable: true,
  38477. configurable: true
  38478. });
  38479. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38480. /**
  38481. * Gets the shadows Saturation value.
  38482. * 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.
  38483. */
  38484. get: function () {
  38485. return this._shadowsSaturation;
  38486. },
  38487. /**
  38488. * Sets the shadows Saturation value.
  38489. * 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.
  38490. */
  38491. set: function (value) {
  38492. this._shadowsSaturation = value;
  38493. this._dirty = true;
  38494. },
  38495. enumerable: true,
  38496. configurable: true
  38497. });
  38498. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38499. /**
  38500. * Gets the shadows Exposure value.
  38501. * 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.
  38502. */
  38503. get: function () {
  38504. return this._shadowsExposure;
  38505. },
  38506. /**
  38507. * Sets the shadows Exposure value.
  38508. * 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.
  38509. */
  38510. set: function (value) {
  38511. this._shadowsExposure = value;
  38512. this._dirty = true;
  38513. },
  38514. enumerable: true,
  38515. configurable: true
  38516. });
  38517. ColorCurves.prototype.getClassName = function () {
  38518. return "ColorCurves";
  38519. };
  38520. /**
  38521. * Binds the color curves to the shader.
  38522. * @param colorCurves The color curve to bind
  38523. * @param effect The effect to bind to
  38524. */
  38525. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38526. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38527. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38528. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38529. if (colorCurves._dirty) {
  38530. colorCurves._dirty = false;
  38531. // Fill in global info.
  38532. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38533. // Compute highlights info.
  38534. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38535. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38536. // Compute midtones info.
  38537. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38538. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38539. // Compute shadows info.
  38540. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38541. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38542. // Compute deltas (neutral is midtones).
  38543. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38544. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38545. }
  38546. if (effect) {
  38547. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38548. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38549. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38550. }
  38551. };
  38552. /**
  38553. * Prepare the list of uniforms associated with the ColorCurves effects.
  38554. * @param uniformsList The list of uniforms used in the effect
  38555. */
  38556. ColorCurves.PrepareUniforms = function (uniformsList) {
  38557. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38558. };
  38559. /**
  38560. * Returns color grading data based on a hue, density, saturation and exposure value.
  38561. * @param filterHue The hue of the color filter.
  38562. * @param filterDensity The density of the color filter.
  38563. * @param saturation The saturation.
  38564. * @param exposure The exposure.
  38565. * @param result The result data container.
  38566. */
  38567. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38568. if (hue == null) {
  38569. return;
  38570. }
  38571. hue = ColorCurves.clamp(hue, 0, 360);
  38572. density = ColorCurves.clamp(density, -100, 100);
  38573. saturation = ColorCurves.clamp(saturation, -100, 100);
  38574. exposure = ColorCurves.clamp(exposure, -100, 100);
  38575. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38576. // so that the maximum filter density is only 50% control. This provides fine control
  38577. // for small values and reasonable range.
  38578. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38579. density *= 0.5;
  38580. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38581. if (density < 0) {
  38582. density *= -1;
  38583. hue = (hue + 180) % 360;
  38584. }
  38585. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38586. result.scaleToRef(2, result);
  38587. result.a = 1 + 0.01 * saturation;
  38588. };
  38589. /**
  38590. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38591. * @param value The input slider value in range [-100,100].
  38592. * @returns Adjusted value.
  38593. */
  38594. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38595. value /= 100;
  38596. var x = Math.abs(value);
  38597. x = Math.pow(x, 2);
  38598. if (value < 0) {
  38599. x *= -1;
  38600. }
  38601. x *= 100;
  38602. return x;
  38603. };
  38604. /**
  38605. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38606. * @param hue The hue (H) input.
  38607. * @param saturation The saturation (S) input.
  38608. * @param brightness The brightness (B) input.
  38609. * @result An RGBA color represented as Vector4.
  38610. */
  38611. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38612. var h = ColorCurves.clamp(hue, 0, 360);
  38613. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38614. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38615. if (s === 0) {
  38616. result.r = v;
  38617. result.g = v;
  38618. result.b = v;
  38619. }
  38620. else {
  38621. // sector 0 to 5
  38622. h /= 60;
  38623. var i = Math.floor(h);
  38624. // fractional part of h
  38625. var f = h - i;
  38626. var p = v * (1 - s);
  38627. var q = v * (1 - s * f);
  38628. var t = v * (1 - s * (1 - f));
  38629. switch (i) {
  38630. case 0:
  38631. result.r = v;
  38632. result.g = t;
  38633. result.b = p;
  38634. break;
  38635. case 1:
  38636. result.r = q;
  38637. result.g = v;
  38638. result.b = p;
  38639. break;
  38640. case 2:
  38641. result.r = p;
  38642. result.g = v;
  38643. result.b = t;
  38644. break;
  38645. case 3:
  38646. result.r = p;
  38647. result.g = q;
  38648. result.b = v;
  38649. break;
  38650. case 4:
  38651. result.r = t;
  38652. result.g = p;
  38653. result.b = v;
  38654. break;
  38655. default:// case 5:
  38656. result.r = v;
  38657. result.g = p;
  38658. result.b = q;
  38659. break;
  38660. }
  38661. }
  38662. result.a = 1;
  38663. };
  38664. /**
  38665. * Returns a value clamped between min and max
  38666. * @param value The value to clamp
  38667. * @param min The minimum of value
  38668. * @param max The maximum of value
  38669. * @returns The clamped value.
  38670. */
  38671. ColorCurves.clamp = function (value, min, max) {
  38672. return Math.min(Math.max(value, min), max);
  38673. };
  38674. /**
  38675. * Clones the current color curve instance.
  38676. * @return The cloned curves
  38677. */
  38678. ColorCurves.prototype.clone = function () {
  38679. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38680. };
  38681. /**
  38682. * Serializes the current color curve instance to a json representation.
  38683. * @return a JSON representation
  38684. */
  38685. ColorCurves.prototype.serialize = function () {
  38686. return BABYLON.SerializationHelper.Serialize(this);
  38687. };
  38688. /**
  38689. * Parses the color curve from a json representation.
  38690. * @param source the JSON source to parse
  38691. * @return The parsed curves
  38692. */
  38693. ColorCurves.Parse = function (source) {
  38694. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38695. };
  38696. __decorate([
  38697. BABYLON.serialize()
  38698. ], ColorCurves.prototype, "_globalHue", void 0);
  38699. __decorate([
  38700. BABYLON.serialize()
  38701. ], ColorCurves.prototype, "_globalDensity", void 0);
  38702. __decorate([
  38703. BABYLON.serialize()
  38704. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38705. __decorate([
  38706. BABYLON.serialize()
  38707. ], ColorCurves.prototype, "_globalExposure", void 0);
  38708. __decorate([
  38709. BABYLON.serialize()
  38710. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38711. __decorate([
  38712. BABYLON.serialize()
  38713. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38714. __decorate([
  38715. BABYLON.serialize()
  38716. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38717. __decorate([
  38718. BABYLON.serialize()
  38719. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38720. __decorate([
  38721. BABYLON.serialize()
  38722. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38723. __decorate([
  38724. BABYLON.serialize()
  38725. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38726. __decorate([
  38727. BABYLON.serialize()
  38728. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38729. __decorate([
  38730. BABYLON.serialize()
  38731. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38732. return ColorCurves;
  38733. }());
  38734. BABYLON.ColorCurves = ColorCurves;
  38735. })(BABYLON || (BABYLON = {}));
  38736. //# sourceMappingURL=babylon.colorCurves.js.map
  38737. "use strict";
  38738. //# sourceMappingURL=babylon.behavior.js.map
  38739. "use strict";
  38740. var BABYLON;
  38741. (function (BABYLON) {
  38742. /**
  38743. * "Static Class" containing the most commonly used helper while dealing with material for
  38744. * rendering purpose.
  38745. *
  38746. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38747. *
  38748. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38749. */
  38750. var MaterialHelper = /** @class */ (function () {
  38751. function MaterialHelper() {
  38752. }
  38753. /**
  38754. * Bind the current view position to an effect.
  38755. * @param effect The effect to be bound
  38756. * @param scene The scene the eyes position is used from
  38757. */
  38758. MaterialHelper.BindEyePosition = function (effect, scene) {
  38759. if (scene._forcedViewPosition) {
  38760. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38761. return;
  38762. }
  38763. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38764. };
  38765. /**
  38766. * Helps preparing the defines values about the UVs in used in the effect.
  38767. * UVs are shared as much as we can accross chanels in the shaders.
  38768. * @param texture The texture we are preparing the UVs for
  38769. * @param defines The defines to update
  38770. * @param key The chanel key "diffuse", "specular"... used in the shader
  38771. */
  38772. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38773. defines._needUVs = true;
  38774. defines[key] = true;
  38775. if (texture.getTextureMatrix().isIdentity(true)) {
  38776. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38777. if (texture.coordinatesIndex === 0) {
  38778. defines["MAINUV1"] = true;
  38779. }
  38780. else {
  38781. defines["MAINUV2"] = true;
  38782. }
  38783. }
  38784. else {
  38785. defines[key + "DIRECTUV"] = 0;
  38786. }
  38787. };
  38788. /**
  38789. * Binds a texture matrix value to its corrsponding uniform
  38790. * @param texture The texture to bind the matrix for
  38791. * @param uniformBuffer The uniform buffer receivin the data
  38792. * @param key The chanel key "diffuse", "specular"... used in the shader
  38793. */
  38794. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38795. var matrix = texture.getTextureMatrix();
  38796. if (!matrix.isIdentity(true)) {
  38797. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38798. }
  38799. };
  38800. /**
  38801. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38802. * @param mesh defines the current mesh
  38803. * @param scene defines the current scene
  38804. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38805. * @param pointsCloud defines if point cloud rendering has to be turned on
  38806. * @param fogEnabled defines if fog has to be turned on
  38807. * @param alphaTest defines if alpha testing has to be turned on
  38808. * @param defines defines the current list of defines
  38809. */
  38810. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38811. if (defines._areMiscDirty) {
  38812. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38813. defines["POINTSIZE"] = pointsCloud;
  38814. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38815. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38816. defines["ALPHATEST"] = alphaTest;
  38817. }
  38818. };
  38819. /**
  38820. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38821. * @param scene defines the current scene
  38822. * @param engine defines the current engine
  38823. * @param defines specifies the list of active defines
  38824. * @param useInstances defines if instances have to be turned on
  38825. * @param useClipPlane defines if clip plane have to be turned on
  38826. */
  38827. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38828. if (useClipPlane === void 0) { useClipPlane = null; }
  38829. var changed = false;
  38830. if (useClipPlane == null) {
  38831. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38832. }
  38833. if (defines["CLIPPLANE"] !== useClipPlane) {
  38834. defines["CLIPPLANE"] = useClipPlane;
  38835. changed = true;
  38836. }
  38837. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38838. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38839. changed = true;
  38840. }
  38841. if (defines["INSTANCES"] !== useInstances) {
  38842. defines["INSTANCES"] = useInstances;
  38843. changed = true;
  38844. }
  38845. if (changed) {
  38846. defines.markAsUnprocessed();
  38847. }
  38848. };
  38849. /**
  38850. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38851. * @param mesh The mesh containing the geometry data we will draw
  38852. * @param defines The defines to update
  38853. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38854. * @param useBones Precise whether bones should be used or not (override mesh info)
  38855. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38856. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38857. * @returns false if defines are considered not dirty and have not been checked
  38858. */
  38859. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38860. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38861. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38862. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38863. return false;
  38864. }
  38865. defines._normals = defines._needNormals;
  38866. defines._uvs = defines._needUVs;
  38867. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38868. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38869. defines["TANGENT"] = true;
  38870. }
  38871. if (defines._needUVs) {
  38872. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38873. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38874. }
  38875. else {
  38876. defines["UV1"] = false;
  38877. defines["UV2"] = false;
  38878. }
  38879. if (useVertexColor) {
  38880. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38881. defines["VERTEXCOLOR"] = hasVertexColors;
  38882. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38883. }
  38884. if (useBones) {
  38885. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38886. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38887. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38888. }
  38889. else {
  38890. defines["NUM_BONE_INFLUENCERS"] = 0;
  38891. defines["BonesPerMesh"] = 0;
  38892. }
  38893. }
  38894. if (useMorphTargets) {
  38895. var manager = mesh.morphTargetManager;
  38896. if (manager) {
  38897. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38898. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38899. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38900. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38901. }
  38902. else {
  38903. defines["MORPHTARGETS_TANGENT"] = false;
  38904. defines["MORPHTARGETS_NORMAL"] = false;
  38905. defines["MORPHTARGETS"] = false;
  38906. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38907. }
  38908. }
  38909. return true;
  38910. };
  38911. /**
  38912. * Prepares the defines related to the light information passed in parameter
  38913. * @param scene The scene we are intending to draw
  38914. * @param mesh The mesh the effect is compiling for
  38915. * @param defines The defines to update
  38916. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38917. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38918. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38919. * @returns true if normals will be required for the rest of the effect
  38920. */
  38921. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38922. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38923. if (disableLighting === void 0) { disableLighting = false; }
  38924. if (!defines._areLightsDirty) {
  38925. return defines._needNormals;
  38926. }
  38927. var lightIndex = 0;
  38928. var needNormals = false;
  38929. var needRebuild = false;
  38930. var lightmapMode = false;
  38931. var shadowEnabled = false;
  38932. var specularEnabled = false;
  38933. if (scene.lightsEnabled && !disableLighting) {
  38934. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38935. var light = _a[_i];
  38936. needNormals = true;
  38937. if (defines["LIGHT" + lightIndex] === undefined) {
  38938. needRebuild = true;
  38939. }
  38940. defines["LIGHT" + lightIndex] = true;
  38941. defines["SPOTLIGHT" + lightIndex] = false;
  38942. defines["HEMILIGHT" + lightIndex] = false;
  38943. defines["POINTLIGHT" + lightIndex] = false;
  38944. defines["DIRLIGHT" + lightIndex] = false;
  38945. var type;
  38946. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38947. type = "SPOTLIGHT" + lightIndex;
  38948. var spotLight = light;
  38949. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38950. }
  38951. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38952. type = "HEMILIGHT" + lightIndex;
  38953. }
  38954. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38955. type = "POINTLIGHT" + lightIndex;
  38956. }
  38957. else {
  38958. type = "DIRLIGHT" + lightIndex;
  38959. }
  38960. defines[type] = true;
  38961. // Specular
  38962. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38963. specularEnabled = true;
  38964. }
  38965. // Shadows
  38966. defines["SHADOW" + lightIndex] = false;
  38967. defines["SHADOWPCF" + lightIndex] = false;
  38968. defines["SHADOWPCSS" + lightIndex] = false;
  38969. defines["SHADOWPOISSON" + lightIndex] = false;
  38970. defines["SHADOWESM" + lightIndex] = false;
  38971. defines["SHADOWCUBE" + lightIndex] = false;
  38972. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  38973. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  38974. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38975. var shadowGenerator = light.getShadowGenerator();
  38976. if (shadowGenerator) {
  38977. shadowEnabled = true;
  38978. shadowGenerator.prepareDefines(defines, lightIndex);
  38979. }
  38980. }
  38981. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38982. lightmapMode = true;
  38983. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38984. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38985. }
  38986. else {
  38987. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38988. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38989. }
  38990. lightIndex++;
  38991. if (lightIndex === maxSimultaneousLights)
  38992. break;
  38993. }
  38994. }
  38995. defines["SPECULARTERM"] = specularEnabled;
  38996. defines["SHADOWS"] = shadowEnabled;
  38997. // Resetting all other lights if any
  38998. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38999. if (defines["LIGHT" + index] !== undefined) {
  39000. defines["LIGHT" + index] = false;
  39001. defines["HEMILIGHT" + lightIndex] = false;
  39002. defines["POINTLIGHT" + lightIndex] = false;
  39003. defines["DIRLIGHT" + lightIndex] = false;
  39004. defines["SPOTLIGHT" + lightIndex] = false;
  39005. defines["SHADOW" + lightIndex] = false;
  39006. }
  39007. }
  39008. var caps = scene.getEngine().getCaps();
  39009. if (defines["SHADOWFLOAT"] === undefined) {
  39010. needRebuild = true;
  39011. }
  39012. defines["SHADOWFLOAT"] = shadowEnabled &&
  39013. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39014. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39015. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39016. if (needRebuild) {
  39017. defines.rebuild();
  39018. }
  39019. return needNormals;
  39020. };
  39021. /**
  39022. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39023. * that won t be acctive due to defines being turned off.
  39024. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39025. * @param samplersList The samplers list
  39026. * @param defines The defines helping in the list generation
  39027. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39028. */
  39029. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39030. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39031. var uniformsList;
  39032. var uniformBuffersList = null;
  39033. if (uniformsListOrOptions.uniformsNames) {
  39034. var options = uniformsListOrOptions;
  39035. uniformsList = options.uniformsNames;
  39036. uniformBuffersList = options.uniformBuffersNames;
  39037. samplersList = options.samplers;
  39038. defines = options.defines;
  39039. maxSimultaneousLights = options.maxSimultaneousLights;
  39040. }
  39041. else {
  39042. uniformsList = uniformsListOrOptions;
  39043. if (!samplersList) {
  39044. samplersList = [];
  39045. }
  39046. }
  39047. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39048. if (!defines["LIGHT" + lightIndex]) {
  39049. break;
  39050. }
  39051. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39052. if (uniformBuffersList) {
  39053. uniformBuffersList.push("Light" + lightIndex);
  39054. }
  39055. samplersList.push("shadowSampler" + lightIndex);
  39056. samplersList.push("depthSampler" + lightIndex);
  39057. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39058. samplersList.push("projectionLightSampler" + lightIndex);
  39059. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39060. }
  39061. }
  39062. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39063. uniformsList.push("morphTargetInfluences");
  39064. }
  39065. };
  39066. /**
  39067. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39068. * @param defines The defines to update while falling back
  39069. * @param fallbacks The authorized effect fallbacks
  39070. * @param maxSimultaneousLights The maximum number of lights allowed
  39071. * @param rank the current rank of the Effect
  39072. * @returns The newly affected rank
  39073. */
  39074. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39075. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39076. if (rank === void 0) { rank = 0; }
  39077. var lightFallbackRank = 0;
  39078. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39079. if (!defines["LIGHT" + lightIndex]) {
  39080. break;
  39081. }
  39082. if (lightIndex > 0) {
  39083. lightFallbackRank = rank + lightIndex;
  39084. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39085. }
  39086. if (!defines["SHADOWS"]) {
  39087. if (defines["SHADOW" + lightIndex]) {
  39088. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39089. }
  39090. if (defines["SHADOWPCF" + lightIndex]) {
  39091. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39092. }
  39093. if (defines["SHADOWPCSS" + lightIndex]) {
  39094. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39095. }
  39096. if (defines["SHADOWPOISSON" + lightIndex]) {
  39097. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39098. }
  39099. if (defines["SHADOWESM" + lightIndex]) {
  39100. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39101. }
  39102. }
  39103. }
  39104. return lightFallbackRank++;
  39105. };
  39106. /**
  39107. * Prepares the list of attributes required for morph targets according to the effect defines.
  39108. * @param attribs The current list of supported attribs
  39109. * @param mesh The mesh to prepare the morph targets attributes for
  39110. * @param defines The current Defines of the effect
  39111. */
  39112. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39113. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39114. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39115. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39116. var manager = mesh.morphTargetManager;
  39117. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39118. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39119. for (var index = 0; index < influencers; index++) {
  39120. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39121. if (normal) {
  39122. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39123. }
  39124. if (tangent) {
  39125. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39126. }
  39127. if (attribs.length > maxAttributesCount) {
  39128. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39129. }
  39130. }
  39131. }
  39132. };
  39133. /**
  39134. * Prepares the list of attributes required for bones according to the effect defines.
  39135. * @param attribs The current list of supported attribs
  39136. * @param mesh The mesh to prepare the bones attributes for
  39137. * @param defines The current Defines of the effect
  39138. * @param fallbacks The current efffect fallback strategy
  39139. */
  39140. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39141. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39142. fallbacks.addCPUSkinningFallback(0, mesh);
  39143. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39144. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39145. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39148. }
  39149. }
  39150. };
  39151. /**
  39152. * Prepares the list of attributes required for instances according to the effect defines.
  39153. * @param attribs The current list of supported attribs
  39154. * @param defines The current Defines of the effect
  39155. */
  39156. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39157. if (defines["INSTANCES"]) {
  39158. attribs.push("world0");
  39159. attribs.push("world1");
  39160. attribs.push("world2");
  39161. attribs.push("world3");
  39162. }
  39163. };
  39164. /**
  39165. * Binds the light shadow information to the effect for the given mesh.
  39166. * @param light The light containing the generator
  39167. * @param scene The scene the lights belongs to
  39168. * @param mesh The mesh we are binding the information to render
  39169. * @param lightIndex The light index in the effect used to render the mesh
  39170. * @param effect The effect we are binding the data to
  39171. */
  39172. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39173. if (light.shadowEnabled && mesh.receiveShadows) {
  39174. var shadowGenerator = light.getShadowGenerator();
  39175. if (shadowGenerator) {
  39176. shadowGenerator.bindShadowLight(lightIndex, effect);
  39177. }
  39178. }
  39179. };
  39180. /**
  39181. * Binds the light information to the effect.
  39182. * @param light The light containing the generator
  39183. * @param effect The effect we are binding the data to
  39184. * @param lightIndex The light index in the effect used to render
  39185. */
  39186. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39187. light.transferToEffect(effect, lightIndex + "");
  39188. };
  39189. /**
  39190. * Binds the lights information from the scene to the effect for the given mesh.
  39191. * @param scene The scene the lights belongs to
  39192. * @param mesh The mesh we are binding the information to render
  39193. * @param effect The effect we are binding the data to
  39194. * @param defines The generated defines for the effect
  39195. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39196. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39197. */
  39198. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39199. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39200. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39201. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39202. for (var i = 0; i < len; i++) {
  39203. var light = mesh._lightSources[i];
  39204. var iAsString = i.toString();
  39205. var scaledIntensity = light.getScaledIntensity();
  39206. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39207. MaterialHelper.BindLightProperties(light, effect, i);
  39208. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39209. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39210. if (defines["SPECULARTERM"]) {
  39211. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39212. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39213. }
  39214. // Shadows
  39215. if (scene.shadowsEnabled) {
  39216. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39217. }
  39218. light._uniformBuffer.update();
  39219. }
  39220. };
  39221. /**
  39222. * Binds the fog information from the scene to the effect for the given mesh.
  39223. * @param scene The scene the lights belongs to
  39224. * @param mesh The mesh we are binding the information to render
  39225. * @param effect The effect we are binding the data to
  39226. */
  39227. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39228. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39229. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39230. effect.setColor3("vFogColor", scene.fogColor);
  39231. }
  39232. };
  39233. /**
  39234. * Binds the bones information from the mesh to the effect.
  39235. * @param mesh The mesh we are binding the information to render
  39236. * @param effect The effect we are binding the data to
  39237. */
  39238. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39239. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39240. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39241. if (matrices && effect) {
  39242. effect.setMatrices("mBones", matrices);
  39243. }
  39244. }
  39245. };
  39246. /**
  39247. * Binds the morph targets information from the mesh to the effect.
  39248. * @param abstractMesh The mesh we are binding the information to render
  39249. * @param effect The effect we are binding the data to
  39250. */
  39251. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39252. var manager = abstractMesh.morphTargetManager;
  39253. if (!abstractMesh || !manager) {
  39254. return;
  39255. }
  39256. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39257. };
  39258. /**
  39259. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39260. * @param defines The generated defines used in the effect
  39261. * @param effect The effect we are binding the data to
  39262. * @param scene The scene we are willing to render with logarithmic scale for
  39263. */
  39264. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39265. if (defines["LOGARITHMICDEPTH"]) {
  39266. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39267. }
  39268. };
  39269. /**
  39270. * Binds the clip plane information from the scene to the effect.
  39271. * @param scene The scene the clip plane information are extracted from
  39272. * @param effect The effect we are binding the data to
  39273. */
  39274. MaterialHelper.BindClipPlane = function (effect, scene) {
  39275. if (scene.clipPlane) {
  39276. var clipPlane = scene.clipPlane;
  39277. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39278. }
  39279. };
  39280. return MaterialHelper;
  39281. }());
  39282. BABYLON.MaterialHelper = MaterialHelper;
  39283. })(BABYLON || (BABYLON = {}));
  39284. //# sourceMappingURL=babylon.materialHelper.js.map
  39285. "use strict";
  39286. var BABYLON;
  39287. (function (BABYLON) {
  39288. var PushMaterial = /** @class */ (function (_super) {
  39289. __extends(PushMaterial, _super);
  39290. function PushMaterial(name, scene) {
  39291. var _this = _super.call(this, name, scene) || this;
  39292. _this._normalMatrix = new BABYLON.Matrix();
  39293. _this.storeEffectOnSubMeshes = true;
  39294. return _this;
  39295. }
  39296. PushMaterial.prototype.getEffect = function () {
  39297. return this._activeEffect;
  39298. };
  39299. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39300. if (!mesh) {
  39301. return false;
  39302. }
  39303. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39304. return true;
  39305. }
  39306. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39307. };
  39308. /**
  39309. * Binds the given world matrix to the active effect
  39310. *
  39311. * @param world the matrix to bind
  39312. */
  39313. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39314. this._activeEffect.setMatrix("world", world);
  39315. };
  39316. /**
  39317. * Binds the given normal matrix to the active effect
  39318. *
  39319. * @param normalMatrix the matrix to bind
  39320. */
  39321. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39322. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39323. };
  39324. PushMaterial.prototype.bind = function (world, mesh) {
  39325. if (!mesh) {
  39326. return;
  39327. }
  39328. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39329. };
  39330. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39331. if (effect === void 0) { effect = null; }
  39332. _super.prototype._afterBind.call(this, mesh);
  39333. this.getScene()._cachedEffect = effect;
  39334. };
  39335. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39336. if (visibility === void 0) { visibility = 1; }
  39337. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39338. };
  39339. return PushMaterial;
  39340. }(BABYLON.Material));
  39341. BABYLON.PushMaterial = PushMaterial;
  39342. })(BABYLON || (BABYLON = {}));
  39343. //# sourceMappingURL=babylon.pushMaterial.js.map
  39344. "use strict";
  39345. var BABYLON;
  39346. (function (BABYLON) {
  39347. /** @ignore */
  39348. var StandardMaterialDefines = /** @class */ (function (_super) {
  39349. __extends(StandardMaterialDefines, _super);
  39350. function StandardMaterialDefines() {
  39351. var _this = _super.call(this) || this;
  39352. _this.MAINUV1 = false;
  39353. _this.MAINUV2 = false;
  39354. _this.DIFFUSE = false;
  39355. _this.DIFFUSEDIRECTUV = 0;
  39356. _this.AMBIENT = false;
  39357. _this.AMBIENTDIRECTUV = 0;
  39358. _this.OPACITY = false;
  39359. _this.OPACITYDIRECTUV = 0;
  39360. _this.OPACITYRGB = false;
  39361. _this.REFLECTION = false;
  39362. _this.EMISSIVE = false;
  39363. _this.EMISSIVEDIRECTUV = 0;
  39364. _this.SPECULAR = false;
  39365. _this.SPECULARDIRECTUV = 0;
  39366. _this.BUMP = false;
  39367. _this.BUMPDIRECTUV = 0;
  39368. _this.PARALLAX = false;
  39369. _this.PARALLAXOCCLUSION = false;
  39370. _this.SPECULAROVERALPHA = false;
  39371. _this.CLIPPLANE = false;
  39372. _this.ALPHATEST = false;
  39373. _this.DEPTHPREPASS = false;
  39374. _this.ALPHAFROMDIFFUSE = false;
  39375. _this.POINTSIZE = false;
  39376. _this.FOG = false;
  39377. _this.SPECULARTERM = false;
  39378. _this.DIFFUSEFRESNEL = false;
  39379. _this.OPACITYFRESNEL = false;
  39380. _this.REFLECTIONFRESNEL = false;
  39381. _this.REFRACTIONFRESNEL = false;
  39382. _this.EMISSIVEFRESNEL = false;
  39383. _this.FRESNEL = false;
  39384. _this.NORMAL = false;
  39385. _this.UV1 = false;
  39386. _this.UV2 = false;
  39387. _this.VERTEXCOLOR = false;
  39388. _this.VERTEXALPHA = false;
  39389. _this.NUM_BONE_INFLUENCERS = 0;
  39390. _this.BonesPerMesh = 0;
  39391. _this.INSTANCES = false;
  39392. _this.GLOSSINESS = false;
  39393. _this.ROUGHNESS = false;
  39394. _this.EMISSIVEASILLUMINATION = false;
  39395. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39396. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39397. _this.LIGHTMAP = false;
  39398. _this.LIGHTMAPDIRECTUV = 0;
  39399. _this.OBJECTSPACE_NORMALMAP = false;
  39400. _this.USELIGHTMAPASSHADOWMAP = false;
  39401. _this.REFLECTIONMAP_3D = false;
  39402. _this.REFLECTIONMAP_SPHERICAL = false;
  39403. _this.REFLECTIONMAP_PLANAR = false;
  39404. _this.REFLECTIONMAP_CUBIC = false;
  39405. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39406. _this.REFLECTIONMAP_PROJECTION = false;
  39407. _this.REFLECTIONMAP_SKYBOX = false;
  39408. _this.REFLECTIONMAP_EXPLICIT = false;
  39409. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39410. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39411. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39412. _this.INVERTCUBICMAP = false;
  39413. _this.LOGARITHMICDEPTH = false;
  39414. _this.REFRACTION = false;
  39415. _this.REFRACTIONMAP_3D = false;
  39416. _this.REFLECTIONOVERALPHA = false;
  39417. _this.TWOSIDEDLIGHTING = false;
  39418. _this.SHADOWFLOAT = false;
  39419. _this.MORPHTARGETS = false;
  39420. _this.MORPHTARGETS_NORMAL = false;
  39421. _this.MORPHTARGETS_TANGENT = false;
  39422. _this.NUM_MORPH_INFLUENCERS = 0;
  39423. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39424. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39425. _this.IMAGEPROCESSING = false;
  39426. _this.VIGNETTE = false;
  39427. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39428. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39429. _this.TONEMAPPING = false;
  39430. _this.CONTRAST = false;
  39431. _this.COLORCURVES = false;
  39432. _this.COLORGRADING = false;
  39433. _this.COLORGRADING3D = false;
  39434. _this.SAMPLER3DGREENDEPTH = false;
  39435. _this.SAMPLER3DBGRMAP = false;
  39436. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39437. _this.EXPOSURE = false;
  39438. _this.rebuild();
  39439. return _this;
  39440. }
  39441. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39442. var modes = [
  39443. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39444. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39445. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39446. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39447. ];
  39448. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39449. var mode = modes_1[_i];
  39450. this[mode] = (mode === modeToEnable);
  39451. }
  39452. };
  39453. return StandardMaterialDefines;
  39454. }(BABYLON.MaterialDefines));
  39455. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39456. var StandardMaterial = /** @class */ (function (_super) {
  39457. __extends(StandardMaterial, _super);
  39458. function StandardMaterial(name, scene) {
  39459. var _this = _super.call(this, name, scene) || this;
  39460. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39461. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39462. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39463. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39464. _this.specularPower = 64;
  39465. _this._useAlphaFromDiffuseTexture = false;
  39466. _this._useEmissiveAsIllumination = false;
  39467. _this._linkEmissiveWithDiffuse = false;
  39468. _this._useSpecularOverAlpha = false;
  39469. _this._useReflectionOverAlpha = false;
  39470. _this._disableLighting = false;
  39471. _this._useObjectSpaceNormalMap = false;
  39472. _this._useParallax = false;
  39473. _this._useParallaxOcclusion = false;
  39474. _this.parallaxScaleBias = 0.05;
  39475. _this._roughness = 0;
  39476. _this.indexOfRefraction = 0.98;
  39477. _this.invertRefractionY = true;
  39478. _this._useLightmapAsShadowmap = false;
  39479. _this._useReflectionFresnelFromSpecular = false;
  39480. _this._useGlossinessFromSpecularMapAlpha = false;
  39481. _this._maxSimultaneousLights = 4;
  39482. /**
  39483. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39484. */
  39485. _this._invertNormalMapX = false;
  39486. /**
  39487. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39488. */
  39489. _this._invertNormalMapY = false;
  39490. /**
  39491. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39492. */
  39493. _this._twoSidedLighting = false;
  39494. _this._renderTargets = new BABYLON.SmartArray(16);
  39495. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39496. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39497. // Setup the default processing configuration to the scene.
  39498. _this._attachImageProcessingConfiguration(null);
  39499. _this.getRenderTargetTextures = function () {
  39500. _this._renderTargets.reset();
  39501. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39502. _this._renderTargets.push(_this._reflectionTexture);
  39503. }
  39504. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39505. _this._renderTargets.push(_this._refractionTexture);
  39506. }
  39507. return _this._renderTargets;
  39508. };
  39509. return _this;
  39510. }
  39511. ;
  39512. ;
  39513. ;
  39514. ;
  39515. ;
  39516. ;
  39517. ;
  39518. ;
  39519. ;
  39520. ;
  39521. ;
  39522. ;
  39523. ;
  39524. ;
  39525. ;
  39526. ;
  39527. ;
  39528. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39529. /**
  39530. * Gets the image processing configuration used either in this material.
  39531. */
  39532. get: function () {
  39533. return this._imageProcessingConfiguration;
  39534. },
  39535. /**
  39536. * Sets the Default image processing configuration used either in the this material.
  39537. *
  39538. * If sets to null, the scene one is in use.
  39539. */
  39540. set: function (value) {
  39541. this._attachImageProcessingConfiguration(value);
  39542. // Ensure the effect will be rebuilt.
  39543. this._markAllSubMeshesAsTexturesDirty();
  39544. },
  39545. enumerable: true,
  39546. configurable: true
  39547. });
  39548. /**
  39549. * Attaches a new image processing configuration to the Standard Material.
  39550. * @param configuration
  39551. */
  39552. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39553. var _this = this;
  39554. if (configuration === this._imageProcessingConfiguration) {
  39555. return;
  39556. }
  39557. // Detaches observer.
  39558. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39559. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39560. }
  39561. // Pick the scene configuration if needed.
  39562. if (!configuration) {
  39563. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39564. }
  39565. else {
  39566. this._imageProcessingConfiguration = configuration;
  39567. }
  39568. // Attaches observer.
  39569. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39570. _this._markAllSubMeshesAsImageProcessingDirty();
  39571. });
  39572. };
  39573. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39574. /**
  39575. * Gets wether the color curves effect is enabled.
  39576. */
  39577. get: function () {
  39578. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39579. },
  39580. /**
  39581. * Sets wether the color curves effect is enabled.
  39582. */
  39583. set: function (value) {
  39584. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39585. },
  39586. enumerable: true,
  39587. configurable: true
  39588. });
  39589. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39590. /**
  39591. * Gets wether the color grading effect is enabled.
  39592. */
  39593. get: function () {
  39594. return this.imageProcessingConfiguration.colorGradingEnabled;
  39595. },
  39596. /**
  39597. * Gets wether the color grading effect is enabled.
  39598. */
  39599. set: function (value) {
  39600. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39601. },
  39602. enumerable: true,
  39603. configurable: true
  39604. });
  39605. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39606. /**
  39607. * Gets wether tonemapping is enabled or not.
  39608. */
  39609. get: function () {
  39610. return this._imageProcessingConfiguration.toneMappingEnabled;
  39611. },
  39612. /**
  39613. * Sets wether tonemapping is enabled or not
  39614. */
  39615. set: function (value) {
  39616. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39617. },
  39618. enumerable: true,
  39619. configurable: true
  39620. });
  39621. ;
  39622. ;
  39623. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39624. /**
  39625. * The camera exposure used on this material.
  39626. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39627. * This corresponds to a photographic exposure.
  39628. */
  39629. get: function () {
  39630. return this._imageProcessingConfiguration.exposure;
  39631. },
  39632. /**
  39633. * The camera exposure used on this material.
  39634. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39635. * This corresponds to a photographic exposure.
  39636. */
  39637. set: function (value) {
  39638. this._imageProcessingConfiguration.exposure = value;
  39639. },
  39640. enumerable: true,
  39641. configurable: true
  39642. });
  39643. ;
  39644. ;
  39645. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39646. /**
  39647. * Gets The camera contrast used on this material.
  39648. */
  39649. get: function () {
  39650. return this._imageProcessingConfiguration.contrast;
  39651. },
  39652. /**
  39653. * Sets The camera contrast used on this material.
  39654. */
  39655. set: function (value) {
  39656. this._imageProcessingConfiguration.contrast = value;
  39657. },
  39658. enumerable: true,
  39659. configurable: true
  39660. });
  39661. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39662. /**
  39663. * Gets the Color Grading 2D Lookup Texture.
  39664. */
  39665. get: function () {
  39666. return this._imageProcessingConfiguration.colorGradingTexture;
  39667. },
  39668. /**
  39669. * Sets the Color Grading 2D Lookup Texture.
  39670. */
  39671. set: function (value) {
  39672. this._imageProcessingConfiguration.colorGradingTexture = value;
  39673. },
  39674. enumerable: true,
  39675. configurable: true
  39676. });
  39677. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39678. /**
  39679. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39680. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39681. * 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;
  39682. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39683. */
  39684. get: function () {
  39685. return this._imageProcessingConfiguration.colorCurves;
  39686. },
  39687. /**
  39688. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39689. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39690. * 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;
  39691. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39692. */
  39693. set: function (value) {
  39694. this._imageProcessingConfiguration.colorCurves = value;
  39695. },
  39696. enumerable: true,
  39697. configurable: true
  39698. });
  39699. StandardMaterial.prototype.getClassName = function () {
  39700. return "StandardMaterial";
  39701. };
  39702. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39703. get: function () {
  39704. return this._useLogarithmicDepth;
  39705. },
  39706. set: function (value) {
  39707. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39708. this._markAllSubMeshesAsMiscDirty();
  39709. },
  39710. enumerable: true,
  39711. configurable: true
  39712. });
  39713. StandardMaterial.prototype.needAlphaBlending = function () {
  39714. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39715. };
  39716. StandardMaterial.prototype.needAlphaTesting = function () {
  39717. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39718. };
  39719. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39720. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39721. };
  39722. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39723. return this._diffuseTexture;
  39724. };
  39725. /**
  39726. * Child classes can use it to update shaders
  39727. */
  39728. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39729. if (useInstances === void 0) { useInstances = false; }
  39730. if (subMesh.effect && this.isFrozen) {
  39731. if (this._wasPreviouslyReady && subMesh.effect) {
  39732. return true;
  39733. }
  39734. }
  39735. if (!subMesh._materialDefines) {
  39736. subMesh._materialDefines = new StandardMaterialDefines();
  39737. }
  39738. var scene = this.getScene();
  39739. var defines = subMesh._materialDefines;
  39740. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39741. if (defines._renderId === scene.getRenderId()) {
  39742. return true;
  39743. }
  39744. }
  39745. var engine = scene.getEngine();
  39746. // Lights
  39747. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39748. // Textures
  39749. if (defines._areTexturesDirty) {
  39750. defines._needUVs = false;
  39751. defines.MAINUV1 = false;
  39752. defines.MAINUV2 = false;
  39753. if (scene.texturesEnabled) {
  39754. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39755. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39756. return false;
  39757. }
  39758. else {
  39759. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39760. }
  39761. }
  39762. else {
  39763. defines.DIFFUSE = false;
  39764. }
  39765. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39766. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39767. return false;
  39768. }
  39769. else {
  39770. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39771. }
  39772. }
  39773. else {
  39774. defines.AMBIENT = false;
  39775. }
  39776. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39777. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39778. return false;
  39779. }
  39780. else {
  39781. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39782. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39783. }
  39784. }
  39785. else {
  39786. defines.OPACITY = false;
  39787. }
  39788. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39789. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39790. return false;
  39791. }
  39792. else {
  39793. defines._needNormals = true;
  39794. defines.REFLECTION = true;
  39795. defines.ROUGHNESS = (this._roughness > 0);
  39796. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39797. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39798. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39799. switch (this._reflectionTexture.coordinatesMode) {
  39800. case BABYLON.Texture.CUBIC_MODE:
  39801. case BABYLON.Texture.INVCUBIC_MODE:
  39802. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39803. break;
  39804. case BABYLON.Texture.EXPLICIT_MODE:
  39805. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39806. break;
  39807. case BABYLON.Texture.PLANAR_MODE:
  39808. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39809. break;
  39810. case BABYLON.Texture.PROJECTION_MODE:
  39811. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39812. break;
  39813. case BABYLON.Texture.SKYBOX_MODE:
  39814. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39815. break;
  39816. case BABYLON.Texture.SPHERICAL_MODE:
  39817. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39818. break;
  39819. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39820. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39821. break;
  39822. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39823. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39824. break;
  39825. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39826. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39827. break;
  39828. }
  39829. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39830. }
  39831. }
  39832. else {
  39833. defines.REFLECTION = false;
  39834. }
  39835. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39836. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39837. return false;
  39838. }
  39839. else {
  39840. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39841. }
  39842. }
  39843. else {
  39844. defines.EMISSIVE = false;
  39845. }
  39846. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39847. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39848. return false;
  39849. }
  39850. else {
  39851. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39852. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39853. }
  39854. }
  39855. else {
  39856. defines.LIGHTMAP = false;
  39857. }
  39858. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39859. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39860. return false;
  39861. }
  39862. else {
  39863. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39864. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39865. }
  39866. }
  39867. else {
  39868. defines.SPECULAR = false;
  39869. }
  39870. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39871. // Bump texure can not be not blocking.
  39872. if (!this._bumpTexture.isReady()) {
  39873. return false;
  39874. }
  39875. else {
  39876. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39877. defines.PARALLAX = this._useParallax;
  39878. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39879. }
  39880. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39881. }
  39882. else {
  39883. defines.BUMP = false;
  39884. }
  39885. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39886. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39887. return false;
  39888. }
  39889. else {
  39890. defines._needUVs = true;
  39891. defines.REFRACTION = true;
  39892. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39893. }
  39894. }
  39895. else {
  39896. defines.REFRACTION = false;
  39897. }
  39898. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39899. }
  39900. else {
  39901. defines.DIFFUSE = false;
  39902. defines.AMBIENT = false;
  39903. defines.OPACITY = false;
  39904. defines.REFLECTION = false;
  39905. defines.EMISSIVE = false;
  39906. defines.LIGHTMAP = false;
  39907. defines.BUMP = false;
  39908. defines.REFRACTION = false;
  39909. }
  39910. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39911. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39912. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39913. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39914. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39915. }
  39916. if (defines._areImageProcessingDirty) {
  39917. if (!this._imageProcessingConfiguration.isReady()) {
  39918. return false;
  39919. }
  39920. this._imageProcessingConfiguration.prepareDefines(defines);
  39921. }
  39922. if (defines._areFresnelDirty) {
  39923. if (StandardMaterial.FresnelEnabled) {
  39924. // Fresnel
  39925. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39926. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39927. this._reflectionFresnelParameters) {
  39928. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39929. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39930. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39931. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39932. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39933. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39934. defines._needNormals = true;
  39935. defines.FRESNEL = true;
  39936. }
  39937. }
  39938. else {
  39939. defines.FRESNEL = false;
  39940. }
  39941. }
  39942. // Misc.
  39943. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39944. // Attribs
  39945. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39946. // Values that need to be evaluated on every frame
  39947. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39948. // Get correct effect
  39949. if (defines.isDirty) {
  39950. defines.markAsProcessed();
  39951. scene.resetCachedMaterial();
  39952. // Fallbacks
  39953. var fallbacks = new BABYLON.EffectFallbacks();
  39954. if (defines.REFLECTION) {
  39955. fallbacks.addFallback(0, "REFLECTION");
  39956. }
  39957. if (defines.SPECULAR) {
  39958. fallbacks.addFallback(0, "SPECULAR");
  39959. }
  39960. if (defines.BUMP) {
  39961. fallbacks.addFallback(0, "BUMP");
  39962. }
  39963. if (defines.PARALLAX) {
  39964. fallbacks.addFallback(1, "PARALLAX");
  39965. }
  39966. if (defines.PARALLAXOCCLUSION) {
  39967. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39968. }
  39969. if (defines.SPECULAROVERALPHA) {
  39970. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39971. }
  39972. if (defines.FOG) {
  39973. fallbacks.addFallback(1, "FOG");
  39974. }
  39975. if (defines.POINTSIZE) {
  39976. fallbacks.addFallback(0, "POINTSIZE");
  39977. }
  39978. if (defines.LOGARITHMICDEPTH) {
  39979. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39980. }
  39981. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39982. if (defines.SPECULARTERM) {
  39983. fallbacks.addFallback(0, "SPECULARTERM");
  39984. }
  39985. if (defines.DIFFUSEFRESNEL) {
  39986. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39987. }
  39988. if (defines.OPACITYFRESNEL) {
  39989. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39990. }
  39991. if (defines.REFLECTIONFRESNEL) {
  39992. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39993. }
  39994. if (defines.EMISSIVEFRESNEL) {
  39995. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39996. }
  39997. if (defines.FRESNEL) {
  39998. fallbacks.addFallback(4, "FRESNEL");
  39999. }
  40000. //Attributes
  40001. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40002. if (defines.NORMAL) {
  40003. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40004. }
  40005. if (defines.UV1) {
  40006. attribs.push(BABYLON.VertexBuffer.UVKind);
  40007. }
  40008. if (defines.UV2) {
  40009. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40010. }
  40011. if (defines.VERTEXCOLOR) {
  40012. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40013. }
  40014. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40015. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40016. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40017. var shaderName = "default";
  40018. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40019. "vFogInfos", "vFogColor", "pointSize",
  40020. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40021. "mBones",
  40022. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40023. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40024. "vReflectionPosition", "vReflectionSize",
  40025. "logarithmicDepthConstant", "vTangentSpaceParams"
  40026. ];
  40027. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40028. var uniformBuffers = ["Material", "Scene"];
  40029. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40030. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40031. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40032. uniformsNames: uniforms,
  40033. uniformBuffersNames: uniformBuffers,
  40034. samplers: samplers,
  40035. defines: defines,
  40036. maxSimultaneousLights: this._maxSimultaneousLights
  40037. });
  40038. if (this.customShaderNameResolve) {
  40039. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40040. }
  40041. var join = defines.toString();
  40042. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40043. attributes: attribs,
  40044. uniformsNames: uniforms,
  40045. uniformBuffersNames: uniformBuffers,
  40046. samplers: samplers,
  40047. defines: join,
  40048. fallbacks: fallbacks,
  40049. onCompiled: this.onCompiled,
  40050. onError: this.onError,
  40051. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40052. }, engine), defines);
  40053. this.buildUniformLayout();
  40054. }
  40055. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40056. return false;
  40057. }
  40058. defines._renderId = scene.getRenderId();
  40059. this._wasPreviouslyReady = true;
  40060. return true;
  40061. };
  40062. StandardMaterial.prototype.buildUniformLayout = function () {
  40063. // Order is important !
  40064. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40065. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40066. this._uniformBuffer.addUniform("opacityParts", 4);
  40067. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40068. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40069. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40070. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40071. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40072. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40073. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40074. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40075. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40076. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40077. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40078. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40079. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40080. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40081. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40082. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40083. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40084. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40085. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40086. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40087. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40088. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40089. this._uniformBuffer.addUniform("specularMatrix", 16);
  40090. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40091. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40092. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40093. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40094. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40095. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40096. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40097. this._uniformBuffer.addUniform("pointSize", 1);
  40098. this._uniformBuffer.create();
  40099. };
  40100. StandardMaterial.prototype.unbind = function () {
  40101. if (this._activeEffect) {
  40102. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40103. this._activeEffect.setTexture("reflection2DSampler", null);
  40104. }
  40105. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40106. this._activeEffect.setTexture("refraction2DSampler", null);
  40107. }
  40108. }
  40109. _super.prototype.unbind.call(this);
  40110. };
  40111. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40112. var scene = this.getScene();
  40113. var defines = subMesh._materialDefines;
  40114. if (!defines) {
  40115. return;
  40116. }
  40117. var effect = subMesh.effect;
  40118. if (!effect) {
  40119. return;
  40120. }
  40121. this._activeEffect = effect;
  40122. // Matrices
  40123. this.bindOnlyWorldMatrix(world);
  40124. // Normal Matrix
  40125. if (defines.OBJECTSPACE_NORMALMAP) {
  40126. world.toNormalMatrix(this._normalMatrix);
  40127. this.bindOnlyNormalMatrix(this._normalMatrix);
  40128. }
  40129. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40130. // Bones
  40131. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40132. if (mustRebind) {
  40133. this._uniformBuffer.bindToEffect(effect, "Material");
  40134. this.bindViewProjection(effect);
  40135. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40136. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40137. // Fresnel
  40138. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40139. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40140. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40141. }
  40142. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40143. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40144. }
  40145. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40146. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40147. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40148. }
  40149. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40150. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40151. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40152. }
  40153. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40154. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40155. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40156. }
  40157. }
  40158. // Textures
  40159. if (scene.texturesEnabled) {
  40160. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40161. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40162. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40163. }
  40164. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40165. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40166. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40167. }
  40168. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40169. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40170. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40171. }
  40172. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40173. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40174. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40175. if (this._reflectionTexture.boundingBoxSize) {
  40176. var cubeTexture = this._reflectionTexture;
  40177. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40178. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40179. }
  40180. }
  40181. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40182. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40183. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40184. }
  40185. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40186. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40187. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40188. }
  40189. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40190. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40191. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40192. }
  40193. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40194. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40195. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40196. if (scene._mirroredCameraPosition) {
  40197. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40198. }
  40199. else {
  40200. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40201. }
  40202. }
  40203. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40204. var depth = 1.0;
  40205. if (!this._refractionTexture.isCube) {
  40206. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40207. if (this._refractionTexture.depth) {
  40208. depth = this._refractionTexture.depth;
  40209. }
  40210. }
  40211. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40212. }
  40213. }
  40214. // Point size
  40215. if (this.pointsCloud) {
  40216. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40217. }
  40218. if (defines.SPECULARTERM) {
  40219. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40220. }
  40221. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40222. // Diffuse
  40223. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40224. }
  40225. // Textures
  40226. if (scene.texturesEnabled) {
  40227. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40228. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40229. }
  40230. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40231. effect.setTexture("ambientSampler", this._ambientTexture);
  40232. }
  40233. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40234. effect.setTexture("opacitySampler", this._opacityTexture);
  40235. }
  40236. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40237. if (this._reflectionTexture.isCube) {
  40238. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40239. }
  40240. else {
  40241. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40242. }
  40243. }
  40244. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40245. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40246. }
  40247. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40248. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40249. }
  40250. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40251. effect.setTexture("specularSampler", this._specularTexture);
  40252. }
  40253. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40254. effect.setTexture("bumpSampler", this._bumpTexture);
  40255. }
  40256. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40257. var depth = 1.0;
  40258. if (this._refractionTexture.isCube) {
  40259. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40260. }
  40261. else {
  40262. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40263. }
  40264. }
  40265. }
  40266. // Clip plane
  40267. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40268. // Colors
  40269. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40270. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40271. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40272. }
  40273. if (mustRebind || !this.isFrozen) {
  40274. // Lights
  40275. if (scene.lightsEnabled && !this._disableLighting) {
  40276. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40277. }
  40278. // View
  40279. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40280. this.bindView(effect);
  40281. }
  40282. // Fog
  40283. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40284. // Morph targets
  40285. if (defines.NUM_MORPH_INFLUENCERS) {
  40286. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40287. }
  40288. // Log. depth
  40289. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40290. // image processing
  40291. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40292. this._imageProcessingConfiguration.bind(this._activeEffect);
  40293. }
  40294. }
  40295. this._uniformBuffer.update();
  40296. this._afterBind(mesh, this._activeEffect);
  40297. };
  40298. StandardMaterial.prototype.getAnimatables = function () {
  40299. var results = [];
  40300. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40301. results.push(this._diffuseTexture);
  40302. }
  40303. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40304. results.push(this._ambientTexture);
  40305. }
  40306. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40307. results.push(this._opacityTexture);
  40308. }
  40309. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40310. results.push(this._reflectionTexture);
  40311. }
  40312. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40313. results.push(this._emissiveTexture);
  40314. }
  40315. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40316. results.push(this._specularTexture);
  40317. }
  40318. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40319. results.push(this._bumpTexture);
  40320. }
  40321. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40322. results.push(this._lightmapTexture);
  40323. }
  40324. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40325. results.push(this._refractionTexture);
  40326. }
  40327. return results;
  40328. };
  40329. StandardMaterial.prototype.getActiveTextures = function () {
  40330. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40331. if (this._diffuseTexture) {
  40332. activeTextures.push(this._diffuseTexture);
  40333. }
  40334. if (this._ambientTexture) {
  40335. activeTextures.push(this._ambientTexture);
  40336. }
  40337. if (this._opacityTexture) {
  40338. activeTextures.push(this._opacityTexture);
  40339. }
  40340. if (this._reflectionTexture) {
  40341. activeTextures.push(this._reflectionTexture);
  40342. }
  40343. if (this._emissiveTexture) {
  40344. activeTextures.push(this._emissiveTexture);
  40345. }
  40346. if (this._specularTexture) {
  40347. activeTextures.push(this._specularTexture);
  40348. }
  40349. if (this._bumpTexture) {
  40350. activeTextures.push(this._bumpTexture);
  40351. }
  40352. if (this._lightmapTexture) {
  40353. activeTextures.push(this._lightmapTexture);
  40354. }
  40355. if (this._refractionTexture) {
  40356. activeTextures.push(this._refractionTexture);
  40357. }
  40358. return activeTextures;
  40359. };
  40360. StandardMaterial.prototype.hasTexture = function (texture) {
  40361. if (_super.prototype.hasTexture.call(this, texture)) {
  40362. return true;
  40363. }
  40364. if (this._diffuseTexture === texture) {
  40365. return true;
  40366. }
  40367. if (this._ambientTexture === texture) {
  40368. return true;
  40369. }
  40370. if (this._opacityTexture === texture) {
  40371. return true;
  40372. }
  40373. if (this._reflectionTexture === texture) {
  40374. return true;
  40375. }
  40376. if (this._emissiveTexture === texture) {
  40377. return true;
  40378. }
  40379. if (this._specularTexture === texture) {
  40380. return true;
  40381. }
  40382. if (this._bumpTexture === texture) {
  40383. return true;
  40384. }
  40385. if (this._lightmapTexture === texture) {
  40386. return true;
  40387. }
  40388. if (this._refractionTexture === texture) {
  40389. return true;
  40390. }
  40391. return false;
  40392. };
  40393. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40394. if (forceDisposeTextures) {
  40395. if (this._diffuseTexture) {
  40396. this._diffuseTexture.dispose();
  40397. }
  40398. if (this._ambientTexture) {
  40399. this._ambientTexture.dispose();
  40400. }
  40401. if (this._opacityTexture) {
  40402. this._opacityTexture.dispose();
  40403. }
  40404. if (this._reflectionTexture) {
  40405. this._reflectionTexture.dispose();
  40406. }
  40407. if (this._emissiveTexture) {
  40408. this._emissiveTexture.dispose();
  40409. }
  40410. if (this._specularTexture) {
  40411. this._specularTexture.dispose();
  40412. }
  40413. if (this._bumpTexture) {
  40414. this._bumpTexture.dispose();
  40415. }
  40416. if (this._lightmapTexture) {
  40417. this._lightmapTexture.dispose();
  40418. }
  40419. if (this._refractionTexture) {
  40420. this._refractionTexture.dispose();
  40421. }
  40422. }
  40423. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40424. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40425. }
  40426. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40427. };
  40428. StandardMaterial.prototype.clone = function (name) {
  40429. var _this = this;
  40430. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40431. result.name = name;
  40432. result.id = name;
  40433. return result;
  40434. };
  40435. StandardMaterial.prototype.serialize = function () {
  40436. return BABYLON.SerializationHelper.Serialize(this);
  40437. };
  40438. // Statics
  40439. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40440. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40441. };
  40442. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40443. get: function () {
  40444. return StandardMaterial._DiffuseTextureEnabled;
  40445. },
  40446. set: function (value) {
  40447. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40448. return;
  40449. }
  40450. StandardMaterial._DiffuseTextureEnabled = value;
  40451. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40452. },
  40453. enumerable: true,
  40454. configurable: true
  40455. });
  40456. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40457. get: function () {
  40458. return StandardMaterial._AmbientTextureEnabled;
  40459. },
  40460. set: function (value) {
  40461. if (StandardMaterial._AmbientTextureEnabled === value) {
  40462. return;
  40463. }
  40464. StandardMaterial._AmbientTextureEnabled = value;
  40465. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40466. },
  40467. enumerable: true,
  40468. configurable: true
  40469. });
  40470. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40471. get: function () {
  40472. return StandardMaterial._OpacityTextureEnabled;
  40473. },
  40474. set: function (value) {
  40475. if (StandardMaterial._OpacityTextureEnabled === value) {
  40476. return;
  40477. }
  40478. StandardMaterial._OpacityTextureEnabled = value;
  40479. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40480. },
  40481. enumerable: true,
  40482. configurable: true
  40483. });
  40484. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40485. get: function () {
  40486. return StandardMaterial._ReflectionTextureEnabled;
  40487. },
  40488. set: function (value) {
  40489. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40490. return;
  40491. }
  40492. StandardMaterial._ReflectionTextureEnabled = value;
  40493. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40494. },
  40495. enumerable: true,
  40496. configurable: true
  40497. });
  40498. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40499. get: function () {
  40500. return StandardMaterial._EmissiveTextureEnabled;
  40501. },
  40502. set: function (value) {
  40503. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40504. return;
  40505. }
  40506. StandardMaterial._EmissiveTextureEnabled = value;
  40507. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40508. },
  40509. enumerable: true,
  40510. configurable: true
  40511. });
  40512. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40513. get: function () {
  40514. return StandardMaterial._SpecularTextureEnabled;
  40515. },
  40516. set: function (value) {
  40517. if (StandardMaterial._SpecularTextureEnabled === value) {
  40518. return;
  40519. }
  40520. StandardMaterial._SpecularTextureEnabled = value;
  40521. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40522. },
  40523. enumerable: true,
  40524. configurable: true
  40525. });
  40526. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40527. get: function () {
  40528. return StandardMaterial._BumpTextureEnabled;
  40529. },
  40530. set: function (value) {
  40531. if (StandardMaterial._BumpTextureEnabled === value) {
  40532. return;
  40533. }
  40534. StandardMaterial._BumpTextureEnabled = value;
  40535. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40536. },
  40537. enumerable: true,
  40538. configurable: true
  40539. });
  40540. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40541. get: function () {
  40542. return StandardMaterial._LightmapTextureEnabled;
  40543. },
  40544. set: function (value) {
  40545. if (StandardMaterial._LightmapTextureEnabled === value) {
  40546. return;
  40547. }
  40548. StandardMaterial._LightmapTextureEnabled = value;
  40549. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40550. },
  40551. enumerable: true,
  40552. configurable: true
  40553. });
  40554. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40555. get: function () {
  40556. return StandardMaterial._RefractionTextureEnabled;
  40557. },
  40558. set: function (value) {
  40559. if (StandardMaterial._RefractionTextureEnabled === value) {
  40560. return;
  40561. }
  40562. StandardMaterial._RefractionTextureEnabled = value;
  40563. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40564. },
  40565. enumerable: true,
  40566. configurable: true
  40567. });
  40568. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40569. get: function () {
  40570. return StandardMaterial._ColorGradingTextureEnabled;
  40571. },
  40572. set: function (value) {
  40573. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40574. return;
  40575. }
  40576. StandardMaterial._ColorGradingTextureEnabled = value;
  40577. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40578. },
  40579. enumerable: true,
  40580. configurable: true
  40581. });
  40582. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40583. get: function () {
  40584. return StandardMaterial._FresnelEnabled;
  40585. },
  40586. set: function (value) {
  40587. if (StandardMaterial._FresnelEnabled === value) {
  40588. return;
  40589. }
  40590. StandardMaterial._FresnelEnabled = value;
  40591. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40592. },
  40593. enumerable: true,
  40594. configurable: true
  40595. });
  40596. // Flags used to enable or disable a type of texture for all Standard Materials
  40597. StandardMaterial._DiffuseTextureEnabled = true;
  40598. StandardMaterial._AmbientTextureEnabled = true;
  40599. StandardMaterial._OpacityTextureEnabled = true;
  40600. StandardMaterial._ReflectionTextureEnabled = true;
  40601. StandardMaterial._EmissiveTextureEnabled = true;
  40602. StandardMaterial._SpecularTextureEnabled = true;
  40603. StandardMaterial._BumpTextureEnabled = true;
  40604. StandardMaterial._LightmapTextureEnabled = true;
  40605. StandardMaterial._RefractionTextureEnabled = true;
  40606. StandardMaterial._ColorGradingTextureEnabled = true;
  40607. StandardMaterial._FresnelEnabled = true;
  40608. __decorate([
  40609. BABYLON.serializeAsTexture("diffuseTexture")
  40610. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40611. __decorate([
  40612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40613. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40614. __decorate([
  40615. BABYLON.serializeAsTexture("ambientTexture")
  40616. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40617. __decorate([
  40618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40619. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40620. __decorate([
  40621. BABYLON.serializeAsTexture("opacityTexture")
  40622. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40623. __decorate([
  40624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40625. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40626. __decorate([
  40627. BABYLON.serializeAsTexture("reflectionTexture")
  40628. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40629. __decorate([
  40630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40631. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40632. __decorate([
  40633. BABYLON.serializeAsTexture("emissiveTexture")
  40634. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40635. __decorate([
  40636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40637. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40638. __decorate([
  40639. BABYLON.serializeAsTexture("specularTexture")
  40640. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40641. __decorate([
  40642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40643. ], StandardMaterial.prototype, "specularTexture", void 0);
  40644. __decorate([
  40645. BABYLON.serializeAsTexture("bumpTexture")
  40646. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40647. __decorate([
  40648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40649. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40650. __decorate([
  40651. BABYLON.serializeAsTexture("lightmapTexture")
  40652. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40653. __decorate([
  40654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40655. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40656. __decorate([
  40657. BABYLON.serializeAsTexture("refractionTexture")
  40658. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40659. __decorate([
  40660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40661. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40662. __decorate([
  40663. BABYLON.serializeAsColor3("ambient")
  40664. ], StandardMaterial.prototype, "ambientColor", void 0);
  40665. __decorate([
  40666. BABYLON.serializeAsColor3("diffuse")
  40667. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40668. __decorate([
  40669. BABYLON.serializeAsColor3("specular")
  40670. ], StandardMaterial.prototype, "specularColor", void 0);
  40671. __decorate([
  40672. BABYLON.serializeAsColor3("emissive")
  40673. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40674. __decorate([
  40675. BABYLON.serialize()
  40676. ], StandardMaterial.prototype, "specularPower", void 0);
  40677. __decorate([
  40678. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40679. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40680. __decorate([
  40681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40682. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40683. __decorate([
  40684. BABYLON.serialize("useEmissiveAsIllumination")
  40685. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40686. __decorate([
  40687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40688. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40689. __decorate([
  40690. BABYLON.serialize("linkEmissiveWithDiffuse")
  40691. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40692. __decorate([
  40693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40694. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40695. __decorate([
  40696. BABYLON.serialize("useSpecularOverAlpha")
  40697. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40698. __decorate([
  40699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40700. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40701. __decorate([
  40702. BABYLON.serialize("useReflectionOverAlpha")
  40703. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40704. __decorate([
  40705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40706. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40707. __decorate([
  40708. BABYLON.serialize("disableLighting")
  40709. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40710. __decorate([
  40711. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40712. ], StandardMaterial.prototype, "disableLighting", void 0);
  40713. __decorate([
  40714. BABYLON.serialize("useObjectSpaceNormalMap")
  40715. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40716. __decorate([
  40717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40718. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40719. __decorate([
  40720. BABYLON.serialize("useParallax")
  40721. ], StandardMaterial.prototype, "_useParallax", void 0);
  40722. __decorate([
  40723. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40724. ], StandardMaterial.prototype, "useParallax", void 0);
  40725. __decorate([
  40726. BABYLON.serialize("useParallaxOcclusion")
  40727. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40728. __decorate([
  40729. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40730. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40731. __decorate([
  40732. BABYLON.serialize()
  40733. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40734. __decorate([
  40735. BABYLON.serialize("roughness")
  40736. ], StandardMaterial.prototype, "_roughness", void 0);
  40737. __decorate([
  40738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40739. ], StandardMaterial.prototype, "roughness", void 0);
  40740. __decorate([
  40741. BABYLON.serialize()
  40742. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40743. __decorate([
  40744. BABYLON.serialize()
  40745. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40746. __decorate([
  40747. BABYLON.serialize("useLightmapAsShadowmap")
  40748. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40749. __decorate([
  40750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40751. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40752. __decorate([
  40753. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40754. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40755. __decorate([
  40756. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40757. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40758. __decorate([
  40759. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40760. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40761. __decorate([
  40762. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40763. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40764. __decorate([
  40765. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40766. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40767. __decorate([
  40768. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40769. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40770. __decorate([
  40771. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40772. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40773. __decorate([
  40774. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40775. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40776. __decorate([
  40777. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40778. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40779. __decorate([
  40780. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40781. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40782. __decorate([
  40783. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40784. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40785. __decorate([
  40786. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40787. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40788. __decorate([
  40789. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40790. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40791. __decorate([
  40792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40793. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40794. __decorate([
  40795. BABYLON.serialize("maxSimultaneousLights")
  40796. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40797. __decorate([
  40798. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40799. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40800. __decorate([
  40801. BABYLON.serialize("invertNormalMapX")
  40802. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40803. __decorate([
  40804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40805. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40806. __decorate([
  40807. BABYLON.serialize("invertNormalMapY")
  40808. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40809. __decorate([
  40810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40811. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40812. __decorate([
  40813. BABYLON.serialize("twoSidedLighting")
  40814. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40815. __decorate([
  40816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40817. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40818. __decorate([
  40819. BABYLON.serialize()
  40820. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40821. return StandardMaterial;
  40822. }(BABYLON.PushMaterial));
  40823. BABYLON.StandardMaterial = StandardMaterial;
  40824. })(BABYLON || (BABYLON = {}));
  40825. //# sourceMappingURL=babylon.standardMaterial.js.map
  40826. "use strict";
  40827. var BABYLON;
  40828. (function (BABYLON) {
  40829. /**
  40830. * Manages the defines for the PBR Material.
  40831. */
  40832. var PBRMaterialDefines = /** @class */ (function (_super) {
  40833. __extends(PBRMaterialDefines, _super);
  40834. /**
  40835. * Initializes the PBR Material defines.
  40836. */
  40837. function PBRMaterialDefines() {
  40838. var _this = _super.call(this) || this;
  40839. _this.PBR = true;
  40840. _this.MAINUV1 = false;
  40841. _this.MAINUV2 = false;
  40842. _this.UV1 = false;
  40843. _this.UV2 = false;
  40844. _this.ALBEDO = false;
  40845. _this.ALBEDODIRECTUV = 0;
  40846. _this.VERTEXCOLOR = false;
  40847. _this.AMBIENT = false;
  40848. _this.AMBIENTDIRECTUV = 0;
  40849. _this.AMBIENTINGRAYSCALE = false;
  40850. _this.OPACITY = false;
  40851. _this.VERTEXALPHA = false;
  40852. _this.OPACITYDIRECTUV = 0;
  40853. _this.OPACITYRGB = false;
  40854. _this.ALPHATEST = false;
  40855. _this.DEPTHPREPASS = false;
  40856. _this.ALPHABLEND = false;
  40857. _this.ALPHAFROMALBEDO = false;
  40858. _this.ALPHATESTVALUE = "0.5";
  40859. _this.SPECULAROVERALPHA = false;
  40860. _this.RADIANCEOVERALPHA = false;
  40861. _this.ALPHAFRESNEL = false;
  40862. _this.LINEARALPHAFRESNEL = false;
  40863. _this.PREMULTIPLYALPHA = false;
  40864. _this.EMISSIVE = false;
  40865. _this.EMISSIVEDIRECTUV = 0;
  40866. _this.REFLECTIVITY = false;
  40867. _this.REFLECTIVITYDIRECTUV = 0;
  40868. _this.SPECULARTERM = false;
  40869. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40870. _this.MICROSURFACEAUTOMATIC = false;
  40871. _this.LODBASEDMICROSFURACE = false;
  40872. _this.MICROSURFACEMAP = false;
  40873. _this.MICROSURFACEMAPDIRECTUV = 0;
  40874. _this.METALLICWORKFLOW = false;
  40875. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40876. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40877. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40878. _this.AOSTOREINMETALMAPRED = false;
  40879. _this.ENVIRONMENTBRDF = false;
  40880. _this.NORMAL = false;
  40881. _this.TANGENT = false;
  40882. _this.BUMP = false;
  40883. _this.BUMPDIRECTUV = 0;
  40884. _this.OBJECTSPACE_NORMALMAP = false;
  40885. _this.PARALLAX = false;
  40886. _this.PARALLAXOCCLUSION = false;
  40887. _this.NORMALXYSCALE = true;
  40888. _this.LIGHTMAP = false;
  40889. _this.LIGHTMAPDIRECTUV = 0;
  40890. _this.USELIGHTMAPASSHADOWMAP = false;
  40891. _this.GAMMALIGHTMAP = false;
  40892. _this.REFLECTION = false;
  40893. _this.REFLECTIONMAP_3D = false;
  40894. _this.REFLECTIONMAP_SPHERICAL = false;
  40895. _this.REFLECTIONMAP_PLANAR = false;
  40896. _this.REFLECTIONMAP_CUBIC = false;
  40897. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40898. _this.REFLECTIONMAP_PROJECTION = false;
  40899. _this.REFLECTIONMAP_SKYBOX = false;
  40900. _this.REFLECTIONMAP_EXPLICIT = false;
  40901. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40902. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40903. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40904. _this.INVERTCUBICMAP = false;
  40905. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40906. _this.USESPHERICALINVERTEX = false;
  40907. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40908. _this.LODINREFLECTIONALPHA = false;
  40909. _this.GAMMAREFLECTION = false;
  40910. _this.RADIANCEOCCLUSION = false;
  40911. _this.HORIZONOCCLUSION = false;
  40912. _this.REFRACTION = false;
  40913. _this.REFRACTIONMAP_3D = false;
  40914. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40915. _this.LODINREFRACTIONALPHA = false;
  40916. _this.GAMMAREFRACTION = false;
  40917. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40918. _this.INSTANCES = false;
  40919. _this.NUM_BONE_INFLUENCERS = 0;
  40920. _this.BonesPerMesh = 0;
  40921. _this.NONUNIFORMSCALING = false;
  40922. _this.MORPHTARGETS = false;
  40923. _this.MORPHTARGETS_NORMAL = false;
  40924. _this.MORPHTARGETS_TANGENT = false;
  40925. _this.NUM_MORPH_INFLUENCERS = 0;
  40926. _this.IMAGEPROCESSING = false;
  40927. _this.VIGNETTE = false;
  40928. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40929. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40930. _this.TONEMAPPING = false;
  40931. _this.CONTRAST = false;
  40932. _this.COLORCURVES = false;
  40933. _this.COLORGRADING = false;
  40934. _this.COLORGRADING3D = false;
  40935. _this.SAMPLER3DGREENDEPTH = false;
  40936. _this.SAMPLER3DBGRMAP = false;
  40937. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40938. _this.EXPOSURE = false;
  40939. _this.USEPHYSICALLIGHTFALLOFF = false;
  40940. _this.TWOSIDEDLIGHTING = false;
  40941. _this.SHADOWFLOAT = false;
  40942. _this.CLIPPLANE = false;
  40943. _this.POINTSIZE = false;
  40944. _this.FOG = false;
  40945. _this.LOGARITHMICDEPTH = false;
  40946. _this.FORCENORMALFORWARD = false;
  40947. _this.UNLIT = false;
  40948. _this.rebuild();
  40949. return _this;
  40950. }
  40951. /**
  40952. * Resets the PBR Material defines.
  40953. */
  40954. PBRMaterialDefines.prototype.reset = function () {
  40955. _super.prototype.reset.call(this);
  40956. this.ALPHATESTVALUE = "0.5";
  40957. this.PBR = true;
  40958. };
  40959. return PBRMaterialDefines;
  40960. }(BABYLON.MaterialDefines));
  40961. /**
  40962. * The Physically based material base class of BJS.
  40963. *
  40964. * This offers the main features of a standard PBR material.
  40965. * For more information, please refer to the documentation :
  40966. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40967. */
  40968. var PBRBaseMaterial = /** @class */ (function (_super) {
  40969. __extends(PBRBaseMaterial, _super);
  40970. /**
  40971. * Instantiates a new PBRMaterial instance.
  40972. *
  40973. * @param name The material name
  40974. * @param scene The scene the material will be use in.
  40975. */
  40976. function PBRBaseMaterial(name, scene) {
  40977. var _this = _super.call(this, name, scene) || this;
  40978. /**
  40979. * Intensity of the direct lights e.g. the four lights available in your scene.
  40980. * This impacts both the direct diffuse and specular highlights.
  40981. */
  40982. _this._directIntensity = 1.0;
  40983. /**
  40984. * Intensity of the emissive part of the material.
  40985. * This helps controlling the emissive effect without modifying the emissive color.
  40986. */
  40987. _this._emissiveIntensity = 1.0;
  40988. /**
  40989. * Intensity of the environment e.g. how much the environment will light the object
  40990. * either through harmonics for rough material or through the refelction for shiny ones.
  40991. */
  40992. _this._environmentIntensity = 1.0;
  40993. /**
  40994. * This is a special control allowing the reduction of the specular highlights coming from the
  40995. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40996. */
  40997. _this._specularIntensity = 1.0;
  40998. /**
  40999. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41000. */
  41001. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41002. /**
  41003. * Debug Control allowing disabling the bump map on this material.
  41004. */
  41005. _this._disableBumpMap = false;
  41006. /**
  41007. * AKA Occlusion Texture Intensity in other nomenclature.
  41008. */
  41009. _this._ambientTextureStrength = 1.0;
  41010. /**
  41011. * The color of a material in ambient lighting.
  41012. */
  41013. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41014. /**
  41015. * AKA Diffuse Color in other nomenclature.
  41016. */
  41017. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41018. /**
  41019. * AKA Specular Color in other nomenclature.
  41020. */
  41021. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41022. /**
  41023. * The color applied when light is reflected from a material.
  41024. */
  41025. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41026. /**
  41027. * The color applied when light is emitted from a material.
  41028. */
  41029. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41030. /**
  41031. * AKA Glossiness in other nomenclature.
  41032. */
  41033. _this._microSurface = 0.9;
  41034. /**
  41035. * source material index of refraction (IOR)' / 'destination material IOR.
  41036. */
  41037. _this._indexOfRefraction = 0.66;
  41038. /**
  41039. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41040. */
  41041. _this._invertRefractionY = false;
  41042. /**
  41043. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41044. * Materials half opaque for instance using refraction could benefit from this control.
  41045. */
  41046. _this._linkRefractionWithTransparency = false;
  41047. /**
  41048. * Specifies that the material will use the light map as a show map.
  41049. */
  41050. _this._useLightmapAsShadowmap = false;
  41051. /**
  41052. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41053. * makes the reflect vector face the model (under horizon).
  41054. */
  41055. _this._useHorizonOcclusion = true;
  41056. /**
  41057. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41058. * too much the area relying on ambient texture to define their ambient occlusion.
  41059. */
  41060. _this._useRadianceOcclusion = true;
  41061. /**
  41062. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41063. */
  41064. _this._useAlphaFromAlbedoTexture = false;
  41065. /**
  41066. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41067. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41068. */
  41069. _this._useSpecularOverAlpha = true;
  41070. /**
  41071. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41072. */
  41073. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41074. /**
  41075. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41076. */
  41077. _this._useRoughnessFromMetallicTextureAlpha = true;
  41078. /**
  41079. * Specifies if the metallic texture contains the roughness information in its green channel.
  41080. */
  41081. _this._useRoughnessFromMetallicTextureGreen = false;
  41082. /**
  41083. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41084. */
  41085. _this._useMetallnessFromMetallicTextureBlue = false;
  41086. /**
  41087. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41088. */
  41089. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41090. /**
  41091. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41092. */
  41093. _this._useAmbientInGrayScale = false;
  41094. /**
  41095. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41096. * The material will try to infer what glossiness each pixel should be.
  41097. */
  41098. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41099. /**
  41100. * BJS is using an harcoded light falloff based on a manually sets up range.
  41101. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41102. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41103. */
  41104. _this._usePhysicalLightFalloff = true;
  41105. /**
  41106. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41107. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41108. */
  41109. _this._useRadianceOverAlpha = true;
  41110. /**
  41111. * Allows using an object space normal map (instead of tangent space).
  41112. */
  41113. _this._useObjectSpaceNormalMap = false;
  41114. /**
  41115. * Allows using the bump map in parallax mode.
  41116. */
  41117. _this._useParallax = false;
  41118. /**
  41119. * Allows using the bump map in parallax occlusion mode.
  41120. */
  41121. _this._useParallaxOcclusion = false;
  41122. /**
  41123. * Controls the scale bias of the parallax mode.
  41124. */
  41125. _this._parallaxScaleBias = 0.05;
  41126. /**
  41127. * If sets to true, disables all the lights affecting the material.
  41128. */
  41129. _this._disableLighting = false;
  41130. /**
  41131. * Number of Simultaneous lights allowed on the material.
  41132. */
  41133. _this._maxSimultaneousLights = 4;
  41134. /**
  41135. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41136. */
  41137. _this._invertNormalMapX = false;
  41138. /**
  41139. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41140. */
  41141. _this._invertNormalMapY = false;
  41142. /**
  41143. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41144. */
  41145. _this._twoSidedLighting = false;
  41146. /**
  41147. * Defines the alpha limits in alpha test mode.
  41148. */
  41149. _this._alphaCutOff = 0.4;
  41150. /**
  41151. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41152. */
  41153. _this._forceAlphaTest = false;
  41154. /**
  41155. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41156. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41157. */
  41158. _this._useAlphaFresnel = false;
  41159. /**
  41160. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41161. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41162. */
  41163. _this._useLinearAlphaFresnel = false;
  41164. /**
  41165. * The transparency mode of the material.
  41166. */
  41167. _this._transparencyMode = null;
  41168. /**
  41169. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41170. * from cos thetav and roughness:
  41171. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41172. */
  41173. _this._environmentBRDFTexture = null;
  41174. /**
  41175. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41176. */
  41177. _this._forceIrradianceInFragment = false;
  41178. /**
  41179. * Force normal to face away from face.
  41180. */
  41181. _this._forceNormalForward = false;
  41182. /**
  41183. * Stores the available render targets.
  41184. */
  41185. _this._renderTargets = new BABYLON.SmartArray(16);
  41186. /**
  41187. * Sets the global ambient color for the material used in lighting calculations.
  41188. */
  41189. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41190. /**
  41191. * If set to true, no lighting calculations will be applied.
  41192. */
  41193. _this._unlit = false;
  41194. // Setup the default processing configuration to the scene.
  41195. _this._attachImageProcessingConfiguration(null);
  41196. _this.getRenderTargetTextures = function () {
  41197. _this._renderTargets.reset();
  41198. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41199. _this._renderTargets.push(_this._reflectionTexture);
  41200. }
  41201. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41202. _this._renderTargets.push(_this._refractionTexture);
  41203. }
  41204. return _this._renderTargets;
  41205. };
  41206. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41207. return _this;
  41208. }
  41209. /**
  41210. * Attaches a new image processing configuration to the PBR Material.
  41211. * @param configuration
  41212. */
  41213. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41214. var _this = this;
  41215. if (configuration === this._imageProcessingConfiguration) {
  41216. return;
  41217. }
  41218. // Detaches observer.
  41219. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41220. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41221. }
  41222. // Pick the scene configuration if needed.
  41223. if (!configuration) {
  41224. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41225. }
  41226. else {
  41227. this._imageProcessingConfiguration = configuration;
  41228. }
  41229. // Attaches observer.
  41230. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41231. _this._markAllSubMeshesAsImageProcessingDirty();
  41232. });
  41233. };
  41234. /**
  41235. * Gets the name of the material class.
  41236. */
  41237. PBRBaseMaterial.prototype.getClassName = function () {
  41238. return "PBRBaseMaterial";
  41239. };
  41240. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41241. /**
  41242. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41243. */
  41244. get: function () {
  41245. return this._useLogarithmicDepth;
  41246. },
  41247. /**
  41248. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41249. */
  41250. set: function (value) {
  41251. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41252. },
  41253. enumerable: true,
  41254. configurable: true
  41255. });
  41256. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41257. /**
  41258. * Gets the current transparency mode.
  41259. */
  41260. get: function () {
  41261. return this._transparencyMode;
  41262. },
  41263. /**
  41264. * Sets the transparency mode of the material.
  41265. */
  41266. set: function (value) {
  41267. if (this._transparencyMode === value) {
  41268. return;
  41269. }
  41270. this._transparencyMode = value;
  41271. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41272. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41273. },
  41274. enumerable: true,
  41275. configurable: true
  41276. });
  41277. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41278. /**
  41279. * Returns true if alpha blending should be disabled.
  41280. */
  41281. get: function () {
  41282. return (this._linkRefractionWithTransparency ||
  41283. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41284. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. /**
  41290. * Specifies whether or not this material should be rendered in alpha blend mode.
  41291. */
  41292. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41293. if (this._disableAlphaBlending) {
  41294. return false;
  41295. }
  41296. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41297. };
  41298. /**
  41299. * Specifies if the mesh will require alpha blending.
  41300. * @param mesh - BJS mesh.
  41301. */
  41302. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41303. if (this._disableAlphaBlending) {
  41304. return false;
  41305. }
  41306. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41307. };
  41308. /**
  41309. * Specifies whether or not this material should be rendered in alpha test mode.
  41310. */
  41311. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41312. if (this._forceAlphaTest) {
  41313. return true;
  41314. }
  41315. if (this._linkRefractionWithTransparency) {
  41316. return false;
  41317. }
  41318. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41319. };
  41320. /**
  41321. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41322. */
  41323. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41324. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41325. };
  41326. /**
  41327. * Gets the texture used for the alpha test.
  41328. */
  41329. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41330. return this._albedoTexture;
  41331. };
  41332. /**
  41333. * Specifies that the submesh is ready to be used.
  41334. * @param mesh - BJS mesh.
  41335. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41336. * @param useInstances - Specifies that instances should be used.
  41337. * @returns - boolean indicating that the submesh is ready or not.
  41338. */
  41339. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41340. if (subMesh.effect && this.isFrozen) {
  41341. if (this._wasPreviouslyReady) {
  41342. return true;
  41343. }
  41344. }
  41345. if (!subMesh._materialDefines) {
  41346. subMesh._materialDefines = new PBRMaterialDefines();
  41347. }
  41348. var defines = subMesh._materialDefines;
  41349. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41350. if (defines._renderId === this.getScene().getRenderId()) {
  41351. return true;
  41352. }
  41353. }
  41354. var scene = this.getScene();
  41355. var engine = scene.getEngine();
  41356. if (defines._areTexturesDirty) {
  41357. if (scene.texturesEnabled) {
  41358. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41359. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41360. return false;
  41361. }
  41362. }
  41363. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41364. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41365. return false;
  41366. }
  41367. }
  41368. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41369. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41370. return false;
  41371. }
  41372. }
  41373. var reflectionTexture = this._getReflectionTexture();
  41374. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41375. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41376. return false;
  41377. }
  41378. }
  41379. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41380. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41381. return false;
  41382. }
  41383. }
  41384. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41385. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41386. return false;
  41387. }
  41388. }
  41389. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41390. if (this._metallicTexture) {
  41391. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41392. return false;
  41393. }
  41394. }
  41395. else if (this._reflectivityTexture) {
  41396. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41397. return false;
  41398. }
  41399. }
  41400. if (this._microSurfaceTexture) {
  41401. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41402. return false;
  41403. }
  41404. }
  41405. }
  41406. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41407. // Bump texture cannot be not blocking.
  41408. if (!this._bumpTexture.isReady()) {
  41409. return false;
  41410. }
  41411. }
  41412. var refractionTexture = this._getRefractionTexture();
  41413. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41414. if (!refractionTexture.isReadyOrNotBlocking()) {
  41415. return false;
  41416. }
  41417. }
  41418. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41419. // This is blocking.
  41420. if (!this._environmentBRDFTexture.isReady()) {
  41421. return false;
  41422. }
  41423. }
  41424. }
  41425. }
  41426. if (defines._areImageProcessingDirty) {
  41427. if (!this._imageProcessingConfiguration.isReady()) {
  41428. return false;
  41429. }
  41430. }
  41431. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41432. mesh.createNormals(true);
  41433. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41434. }
  41435. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41436. if (effect) {
  41437. scene.resetCachedMaterial();
  41438. subMesh.setEffect(effect, defines);
  41439. this.buildUniformLayout();
  41440. }
  41441. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41442. return false;
  41443. }
  41444. defines._renderId = scene.getRenderId();
  41445. this._wasPreviouslyReady = true;
  41446. return true;
  41447. };
  41448. /**
  41449. * Specifies if the material uses metallic roughness workflow.
  41450. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41451. */
  41452. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41453. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41454. return true;
  41455. }
  41456. return false;
  41457. };
  41458. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41459. if (onCompiled === void 0) { onCompiled = null; }
  41460. if (onError === void 0) { onError = null; }
  41461. if (useInstances === void 0) { useInstances = null; }
  41462. if (useClipPlane === void 0) { useClipPlane = null; }
  41463. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41464. if (!defines.isDirty) {
  41465. return null;
  41466. }
  41467. defines.markAsProcessed();
  41468. var scene = this.getScene();
  41469. var engine = scene.getEngine();
  41470. // Fallbacks
  41471. var fallbacks = new BABYLON.EffectFallbacks();
  41472. var fallbackRank = 0;
  41473. if (defines.USESPHERICALINVERTEX) {
  41474. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41475. }
  41476. if (defines.FOG) {
  41477. fallbacks.addFallback(fallbackRank, "FOG");
  41478. }
  41479. if (defines.POINTSIZE) {
  41480. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41481. }
  41482. if (defines.LOGARITHMICDEPTH) {
  41483. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41484. }
  41485. if (defines.PARALLAX) {
  41486. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41487. }
  41488. if (defines.PARALLAXOCCLUSION) {
  41489. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41490. }
  41491. if (defines.ENVIRONMENTBRDF) {
  41492. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41493. }
  41494. if (defines.TANGENT) {
  41495. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41496. }
  41497. if (defines.BUMP) {
  41498. fallbacks.addFallback(fallbackRank++, "BUMP");
  41499. }
  41500. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41501. if (defines.SPECULARTERM) {
  41502. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41503. }
  41504. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41505. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41506. }
  41507. if (defines.LIGHTMAP) {
  41508. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41509. }
  41510. if (defines.NORMAL) {
  41511. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41512. }
  41513. if (defines.AMBIENT) {
  41514. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41515. }
  41516. if (defines.EMISSIVE) {
  41517. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41518. }
  41519. if (defines.VERTEXCOLOR) {
  41520. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41521. }
  41522. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41523. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41524. }
  41525. if (defines.MORPHTARGETS) {
  41526. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41527. }
  41528. //Attributes
  41529. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41530. if (defines.NORMAL) {
  41531. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41532. }
  41533. if (defines.TANGENT) {
  41534. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41535. }
  41536. if (defines.UV1) {
  41537. attribs.push(BABYLON.VertexBuffer.UVKind);
  41538. }
  41539. if (defines.UV2) {
  41540. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41541. }
  41542. if (defines.VERTEXCOLOR) {
  41543. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41544. }
  41545. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41546. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41547. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41548. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41549. "vFogInfos", "vFogColor", "pointSize",
  41550. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41551. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41552. "mBones",
  41553. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41554. "vLightingIntensity",
  41555. "logarithmicDepthConstant",
  41556. "vSphericalX", "vSphericalY", "vSphericalZ",
  41557. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41558. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41559. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41560. "vTangentSpaceParams"
  41561. ];
  41562. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41563. "bumpSampler", "lightmapSampler", "opacitySampler",
  41564. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41565. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41566. "microSurfaceSampler", "environmentBrdfSampler"];
  41567. var uniformBuffers = ["Material", "Scene"];
  41568. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41569. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41570. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41571. uniformsNames: uniforms,
  41572. uniformBuffersNames: uniformBuffers,
  41573. samplers: samplers,
  41574. defines: defines,
  41575. maxSimultaneousLights: this._maxSimultaneousLights
  41576. });
  41577. var join = defines.toString();
  41578. return engine.createEffect("pbr", {
  41579. attributes: attribs,
  41580. uniformsNames: uniforms,
  41581. uniformBuffersNames: uniformBuffers,
  41582. samplers: samplers,
  41583. defines: join,
  41584. fallbacks: fallbacks,
  41585. onCompiled: onCompiled,
  41586. onError: onError,
  41587. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41588. }, engine);
  41589. };
  41590. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41591. if (useInstances === void 0) { useInstances = null; }
  41592. if (useClipPlane === void 0) { useClipPlane = null; }
  41593. var scene = this.getScene();
  41594. var engine = scene.getEngine();
  41595. // Lights
  41596. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41597. defines._needNormals = true;
  41598. // Textures
  41599. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41600. if (defines._areTexturesDirty) {
  41601. defines._needUVs = false;
  41602. if (scene.texturesEnabled) {
  41603. if (scene.getEngine().getCaps().textureLOD) {
  41604. defines.LODBASEDMICROSFURACE = true;
  41605. }
  41606. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41607. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41608. }
  41609. else {
  41610. defines.ALBEDO = false;
  41611. }
  41612. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41613. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41614. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41615. }
  41616. else {
  41617. defines.AMBIENT = false;
  41618. }
  41619. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41620. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41621. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41622. }
  41623. else {
  41624. defines.OPACITY = false;
  41625. }
  41626. var reflectionTexture = this._getReflectionTexture();
  41627. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41628. defines.REFLECTION = true;
  41629. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41630. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41631. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41632. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41633. defines.INVERTCUBICMAP = true;
  41634. }
  41635. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41636. switch (reflectionTexture.coordinatesMode) {
  41637. case BABYLON.Texture.CUBIC_MODE:
  41638. case BABYLON.Texture.INVCUBIC_MODE:
  41639. defines.REFLECTIONMAP_CUBIC = true;
  41640. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41641. break;
  41642. case BABYLON.Texture.EXPLICIT_MODE:
  41643. defines.REFLECTIONMAP_EXPLICIT = true;
  41644. break;
  41645. case BABYLON.Texture.PLANAR_MODE:
  41646. defines.REFLECTIONMAP_PLANAR = true;
  41647. break;
  41648. case BABYLON.Texture.PROJECTION_MODE:
  41649. defines.REFLECTIONMAP_PROJECTION = true;
  41650. break;
  41651. case BABYLON.Texture.SKYBOX_MODE:
  41652. defines.REFLECTIONMAP_SKYBOX = true;
  41653. break;
  41654. case BABYLON.Texture.SPHERICAL_MODE:
  41655. defines.REFLECTIONMAP_SPHERICAL = true;
  41656. break;
  41657. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41658. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41659. break;
  41660. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41661. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41662. break;
  41663. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41664. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41665. break;
  41666. }
  41667. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41668. if (reflectionTexture.sphericalPolynomial) {
  41669. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41670. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41671. defines.USESPHERICALINVERTEX = false;
  41672. }
  41673. else {
  41674. defines.USESPHERICALINVERTEX = true;
  41675. }
  41676. }
  41677. }
  41678. }
  41679. else {
  41680. defines.REFLECTION = false;
  41681. defines.REFLECTIONMAP_3D = false;
  41682. defines.REFLECTIONMAP_SPHERICAL = false;
  41683. defines.REFLECTIONMAP_PLANAR = false;
  41684. defines.REFLECTIONMAP_CUBIC = false;
  41685. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41686. defines.REFLECTIONMAP_PROJECTION = false;
  41687. defines.REFLECTIONMAP_SKYBOX = false;
  41688. defines.REFLECTIONMAP_EXPLICIT = false;
  41689. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41690. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41691. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41692. defines.INVERTCUBICMAP = false;
  41693. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41694. defines.USESPHERICALINVERTEX = false;
  41695. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41696. defines.LODINREFLECTIONALPHA = false;
  41697. defines.GAMMAREFLECTION = false;
  41698. }
  41699. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41700. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41701. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41702. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41703. }
  41704. else {
  41705. defines.LIGHTMAP = false;
  41706. }
  41707. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41708. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41709. }
  41710. else {
  41711. defines.EMISSIVE = false;
  41712. }
  41713. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41714. if (this._metallicTexture) {
  41715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41716. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41717. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41718. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41719. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41720. }
  41721. else if (this._reflectivityTexture) {
  41722. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41723. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41724. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41725. }
  41726. else {
  41727. defines.REFLECTIVITY = false;
  41728. }
  41729. if (this._microSurfaceTexture) {
  41730. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41731. }
  41732. else {
  41733. defines.MICROSURFACEMAP = false;
  41734. }
  41735. }
  41736. else {
  41737. defines.REFLECTIVITY = false;
  41738. defines.MICROSURFACEMAP = false;
  41739. }
  41740. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41741. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41742. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41743. defines.PARALLAX = true;
  41744. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41745. }
  41746. else {
  41747. defines.PARALLAX = false;
  41748. }
  41749. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41750. }
  41751. else {
  41752. defines.BUMP = false;
  41753. }
  41754. var refractionTexture = this._getRefractionTexture();
  41755. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41756. defines.REFRACTION = true;
  41757. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41758. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41759. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41760. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41761. if (this._linkRefractionWithTransparency) {
  41762. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41763. }
  41764. }
  41765. else {
  41766. defines.REFRACTION = false;
  41767. }
  41768. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41769. defines.ENVIRONMENTBRDF = true;
  41770. }
  41771. else {
  41772. defines.ENVIRONMENTBRDF = false;
  41773. }
  41774. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41775. defines.ALPHAFROMALBEDO = true;
  41776. }
  41777. else {
  41778. defines.ALPHAFROMALBEDO = false;
  41779. }
  41780. }
  41781. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41782. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41783. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41784. if (!this.backFaceCulling && this._twoSidedLighting) {
  41785. defines.TWOSIDEDLIGHTING = true;
  41786. }
  41787. else {
  41788. defines.TWOSIDEDLIGHTING = false;
  41789. }
  41790. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41791. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41792. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41793. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41794. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41795. }
  41796. if (defines._areImageProcessingDirty) {
  41797. this._imageProcessingConfiguration.prepareDefines(defines);
  41798. }
  41799. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41800. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41801. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41802. // Misc.
  41803. if (defines._areMiscDirty) {
  41804. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41805. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41806. }
  41807. // Values that need to be evaluated on every frame
  41808. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41809. // Attribs
  41810. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41811. };
  41812. /**
  41813. * Force shader compilation
  41814. */
  41815. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41816. var _this = this;
  41817. var localOptions = __assign({ clipPlane: false }, options);
  41818. var defines = new PBRMaterialDefines();
  41819. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41820. if (effect.isReady()) {
  41821. if (onCompiled) {
  41822. onCompiled(this);
  41823. }
  41824. }
  41825. else {
  41826. effect.onCompileObservable.add(function () {
  41827. if (onCompiled) {
  41828. onCompiled(_this);
  41829. }
  41830. });
  41831. }
  41832. };
  41833. /**
  41834. * Initializes the uniform buffer layout for the shader.
  41835. */
  41836. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41837. // Order is important !
  41838. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41839. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41840. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41841. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41842. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41843. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41844. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41845. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41846. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41847. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41848. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41849. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41850. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41851. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41852. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41853. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41854. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41855. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41856. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41857. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41858. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41859. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41860. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41861. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41862. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41863. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41864. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41865. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41866. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41867. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41868. this._uniformBuffer.addUniform("pointSize", 1);
  41869. this._uniformBuffer.create();
  41870. };
  41871. /**
  41872. * Unbinds the textures.
  41873. */
  41874. PBRBaseMaterial.prototype.unbind = function () {
  41875. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41876. this._uniformBuffer.setTexture("reflectionSampler", null);
  41877. }
  41878. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41879. this._uniformBuffer.setTexture("refractionSampler", null);
  41880. }
  41881. _super.prototype.unbind.call(this);
  41882. };
  41883. /**
  41884. * Binds the submesh data.
  41885. * @param world - The world matrix.
  41886. * @param mesh - The BJS mesh.
  41887. * @param subMesh - A submesh of the BJS mesh.
  41888. */
  41889. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41890. var scene = this.getScene();
  41891. var defines = subMesh._materialDefines;
  41892. if (!defines) {
  41893. return;
  41894. }
  41895. var effect = subMesh.effect;
  41896. if (!effect) {
  41897. return;
  41898. }
  41899. this._activeEffect = effect;
  41900. // Matrices
  41901. this.bindOnlyWorldMatrix(world);
  41902. // Normal Matrix
  41903. if (defines.OBJECTSPACE_NORMALMAP) {
  41904. world.toNormalMatrix(this._normalMatrix);
  41905. this.bindOnlyNormalMatrix(this._normalMatrix);
  41906. }
  41907. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41908. // Bones
  41909. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41910. var reflectionTexture = null;
  41911. if (mustRebind) {
  41912. this._uniformBuffer.bindToEffect(effect, "Material");
  41913. this.bindViewProjection(effect);
  41914. reflectionTexture = this._getReflectionTexture();
  41915. var refractionTexture = this._getRefractionTexture();
  41916. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41917. // Texture uniforms
  41918. if (scene.texturesEnabled) {
  41919. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41920. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41921. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41922. }
  41923. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41924. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41925. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41926. }
  41927. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41928. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41929. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41930. }
  41931. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41932. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41933. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41934. if (reflectionTexture.boundingBoxSize) {
  41935. var cubeTexture = reflectionTexture;
  41936. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41937. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41938. }
  41939. var polynomials = reflectionTexture.sphericalPolynomial;
  41940. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41941. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41942. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41943. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41944. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41945. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41946. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41947. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41948. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41949. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41950. }
  41951. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41952. }
  41953. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41954. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41955. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41956. }
  41957. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41958. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41959. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41960. }
  41961. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41962. if (this._metallicTexture) {
  41963. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41964. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41965. }
  41966. else if (this._reflectivityTexture) {
  41967. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41968. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41969. }
  41970. if (this._microSurfaceTexture) {
  41971. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41972. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41973. }
  41974. }
  41975. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41976. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41977. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41978. if (scene._mirroredCameraPosition) {
  41979. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41980. }
  41981. else {
  41982. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41983. }
  41984. }
  41985. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41986. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41987. var depth = 1.0;
  41988. if (!refractionTexture.isCube) {
  41989. if (refractionTexture.depth) {
  41990. depth = refractionTexture.depth;
  41991. }
  41992. }
  41993. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41994. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41995. }
  41996. }
  41997. // Point size
  41998. if (this.pointsCloud) {
  41999. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42000. }
  42001. // Colors
  42002. if (defines.METALLICWORKFLOW) {
  42003. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42004. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42005. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42006. }
  42007. else {
  42008. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42009. }
  42010. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42011. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42012. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42013. // Misc
  42014. this._lightingInfos.x = this._directIntensity;
  42015. this._lightingInfos.y = this._emissiveIntensity;
  42016. this._lightingInfos.z = this._environmentIntensity;
  42017. this._lightingInfos.w = this._specularIntensity;
  42018. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42019. }
  42020. // Textures
  42021. if (scene.texturesEnabled) {
  42022. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42023. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42024. }
  42025. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42026. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42027. }
  42028. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42029. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42030. }
  42031. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42032. if (defines.LODBASEDMICROSFURACE) {
  42033. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42034. }
  42035. else {
  42036. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42037. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42038. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42039. }
  42040. }
  42041. if (defines.ENVIRONMENTBRDF) {
  42042. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42043. }
  42044. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42045. if (defines.LODBASEDMICROSFURACE) {
  42046. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42047. }
  42048. else {
  42049. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42050. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42051. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42052. }
  42053. }
  42054. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42055. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42056. }
  42057. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42058. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42059. }
  42060. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42061. if (this._metallicTexture) {
  42062. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42063. }
  42064. else if (this._reflectivityTexture) {
  42065. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42066. }
  42067. if (this._microSurfaceTexture) {
  42068. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42069. }
  42070. }
  42071. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42072. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42073. }
  42074. }
  42075. // Clip plane
  42076. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42077. // Colors
  42078. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42079. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42080. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42081. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42082. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42083. }
  42084. if (mustRebind || !this.isFrozen) {
  42085. // Lights
  42086. if (scene.lightsEnabled && !this._disableLighting) {
  42087. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42088. }
  42089. // View
  42090. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42091. this.bindView(effect);
  42092. }
  42093. // Fog
  42094. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42095. // Morph targets
  42096. if (defines.NUM_MORPH_INFLUENCERS) {
  42097. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42098. }
  42099. // image processing
  42100. this._imageProcessingConfiguration.bind(this._activeEffect);
  42101. // Log. depth
  42102. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42103. }
  42104. this._uniformBuffer.update();
  42105. this._afterBind(mesh);
  42106. };
  42107. /**
  42108. * Returns the animatable textures.
  42109. * @returns - Array of animatable textures.
  42110. */
  42111. PBRBaseMaterial.prototype.getAnimatables = function () {
  42112. var results = [];
  42113. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42114. results.push(this._albedoTexture);
  42115. }
  42116. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42117. results.push(this._ambientTexture);
  42118. }
  42119. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42120. results.push(this._opacityTexture);
  42121. }
  42122. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42123. results.push(this._reflectionTexture);
  42124. }
  42125. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42126. results.push(this._emissiveTexture);
  42127. }
  42128. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42129. results.push(this._metallicTexture);
  42130. }
  42131. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42132. results.push(this._reflectivityTexture);
  42133. }
  42134. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42135. results.push(this._bumpTexture);
  42136. }
  42137. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42138. results.push(this._lightmapTexture);
  42139. }
  42140. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42141. results.push(this._refractionTexture);
  42142. }
  42143. return results;
  42144. };
  42145. /**
  42146. * Returns the texture used for reflections.
  42147. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42148. */
  42149. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42150. if (this._reflectionTexture) {
  42151. return this._reflectionTexture;
  42152. }
  42153. return this.getScene().environmentTexture;
  42154. };
  42155. /**
  42156. * Returns the texture used for refraction or null if none is used.
  42157. * @returns - Refection texture if present. If no refraction texture and refraction
  42158. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42159. */
  42160. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42161. if (this._refractionTexture) {
  42162. return this._refractionTexture;
  42163. }
  42164. if (this._linkRefractionWithTransparency) {
  42165. return this.getScene().environmentTexture;
  42166. }
  42167. return null;
  42168. };
  42169. /**
  42170. * Disposes the resources of the material.
  42171. * @param forceDisposeEffect - Forces the disposal of effects.
  42172. * @param forceDisposeTextures - Forces the disposal of all textures.
  42173. */
  42174. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42175. if (forceDisposeTextures) {
  42176. if (this._albedoTexture) {
  42177. this._albedoTexture.dispose();
  42178. }
  42179. if (this._ambientTexture) {
  42180. this._ambientTexture.dispose();
  42181. }
  42182. if (this._opacityTexture) {
  42183. this._opacityTexture.dispose();
  42184. }
  42185. if (this._reflectionTexture) {
  42186. this._reflectionTexture.dispose();
  42187. }
  42188. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42189. this._environmentBRDFTexture.dispose();
  42190. }
  42191. if (this._emissiveTexture) {
  42192. this._emissiveTexture.dispose();
  42193. }
  42194. if (this._metallicTexture) {
  42195. this._metallicTexture.dispose();
  42196. }
  42197. if (this._reflectivityTexture) {
  42198. this._reflectivityTexture.dispose();
  42199. }
  42200. if (this._bumpTexture) {
  42201. this._bumpTexture.dispose();
  42202. }
  42203. if (this._lightmapTexture) {
  42204. this._lightmapTexture.dispose();
  42205. }
  42206. if (this._refractionTexture) {
  42207. this._refractionTexture.dispose();
  42208. }
  42209. }
  42210. this._renderTargets.dispose();
  42211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42213. }
  42214. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42215. };
  42216. /**
  42217. * Stores the reflectivity values based on metallic roughness workflow.
  42218. */
  42219. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42220. __decorate([
  42221. BABYLON.serializeAsImageProcessingConfiguration()
  42222. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42223. __decorate([
  42224. BABYLON.serialize()
  42225. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42226. __decorate([
  42227. BABYLON.serialize()
  42228. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42229. return PBRBaseMaterial;
  42230. }(BABYLON.PushMaterial));
  42231. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42232. })(BABYLON || (BABYLON = {}));
  42233. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42234. "use strict";
  42235. var BABYLON;
  42236. (function (BABYLON) {
  42237. /**
  42238. * The Physically based simple base material of BJS.
  42239. *
  42240. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42241. * It is used as the base class for both the specGloss and metalRough conventions.
  42242. */
  42243. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42244. __extends(PBRBaseSimpleMaterial, _super);
  42245. /**
  42246. * Instantiates a new PBRMaterial instance.
  42247. *
  42248. * @param name The material name
  42249. * @param scene The scene the material will be use in.
  42250. */
  42251. function PBRBaseSimpleMaterial(name, scene) {
  42252. var _this = _super.call(this, name, scene) || this;
  42253. /**
  42254. * Number of Simultaneous lights allowed on the material.
  42255. */
  42256. _this.maxSimultaneousLights = 4;
  42257. /**
  42258. * If sets to true, disables all the lights affecting the material.
  42259. */
  42260. _this.disableLighting = false;
  42261. /**
  42262. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42263. */
  42264. _this.invertNormalMapX = false;
  42265. /**
  42266. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42267. */
  42268. _this.invertNormalMapY = false;
  42269. /**
  42270. * Emissivie color used to self-illuminate the model.
  42271. */
  42272. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42273. /**
  42274. * Occlusion Channel Strenght.
  42275. */
  42276. _this.occlusionStrength = 1.0;
  42277. _this.useLightmapAsShadowmap = false;
  42278. _this._useAlphaFromAlbedoTexture = true;
  42279. _this._useAmbientInGrayScale = true;
  42280. return _this;
  42281. }
  42282. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42283. /**
  42284. * Gets the current double sided mode.
  42285. */
  42286. get: function () {
  42287. return this._twoSidedLighting;
  42288. },
  42289. /**
  42290. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42291. */
  42292. set: function (value) {
  42293. if (this._twoSidedLighting === value) {
  42294. return;
  42295. }
  42296. this._twoSidedLighting = value;
  42297. this.backFaceCulling = !value;
  42298. this._markAllSubMeshesAsTexturesDirty();
  42299. },
  42300. enumerable: true,
  42301. configurable: true
  42302. });
  42303. /**
  42304. * Return the active textures of the material.
  42305. */
  42306. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42307. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42308. if (this.environmentTexture) {
  42309. activeTextures.push(this.environmentTexture);
  42310. }
  42311. if (this.normalTexture) {
  42312. activeTextures.push(this.normalTexture);
  42313. }
  42314. if (this.emissiveTexture) {
  42315. activeTextures.push(this.emissiveTexture);
  42316. }
  42317. if (this.occlusionTexture) {
  42318. activeTextures.push(this.occlusionTexture);
  42319. }
  42320. if (this.lightmapTexture) {
  42321. activeTextures.push(this.lightmapTexture);
  42322. }
  42323. return activeTextures;
  42324. };
  42325. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42326. if (_super.prototype.hasTexture.call(this, texture)) {
  42327. return true;
  42328. }
  42329. if (this.lightmapTexture === texture) {
  42330. return true;
  42331. }
  42332. return false;
  42333. };
  42334. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42335. return "PBRBaseSimpleMaterial";
  42336. };
  42337. __decorate([
  42338. BABYLON.serialize(),
  42339. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42340. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42341. __decorate([
  42342. BABYLON.serialize(),
  42343. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42344. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42345. __decorate([
  42346. BABYLON.serializeAsTexture(),
  42347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42348. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42349. __decorate([
  42350. BABYLON.serialize(),
  42351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42352. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42353. __decorate([
  42354. BABYLON.serialize(),
  42355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42356. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42357. __decorate([
  42358. BABYLON.serializeAsTexture(),
  42359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42360. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42361. __decorate([
  42362. BABYLON.serializeAsColor3("emissive"),
  42363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42364. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42365. __decorate([
  42366. BABYLON.serializeAsTexture(),
  42367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42368. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42369. __decorate([
  42370. BABYLON.serialize(),
  42371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42372. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42373. __decorate([
  42374. BABYLON.serializeAsTexture(),
  42375. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42376. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42377. __decorate([
  42378. BABYLON.serialize(),
  42379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42380. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42381. __decorate([
  42382. BABYLON.serialize()
  42383. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42384. __decorate([
  42385. BABYLON.serializeAsTexture(),
  42386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42387. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42388. __decorate([
  42389. BABYLON.serialize(),
  42390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42391. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42392. return PBRBaseSimpleMaterial;
  42393. }(BABYLON.PBRBaseMaterial));
  42394. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42395. })(BABYLON || (BABYLON = {}));
  42396. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42397. "use strict";
  42398. var BABYLON;
  42399. (function (BABYLON) {
  42400. /**
  42401. * The Physically based material of BJS.
  42402. *
  42403. * This offers the main features of a standard PBR material.
  42404. * For more information, please refer to the documentation :
  42405. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42406. */
  42407. var PBRMaterial = /** @class */ (function (_super) {
  42408. __extends(PBRMaterial, _super);
  42409. /**
  42410. * Instantiates a new PBRMaterial instance.
  42411. *
  42412. * @param name The material name
  42413. * @param scene The scene the material will be use in.
  42414. */
  42415. function PBRMaterial(name, scene) {
  42416. var _this = _super.call(this, name, scene) || this;
  42417. /**
  42418. * Intensity of the direct lights e.g. the four lights available in your scene.
  42419. * This impacts both the direct diffuse and specular highlights.
  42420. */
  42421. _this.directIntensity = 1.0;
  42422. /**
  42423. * Intensity of the emissive part of the material.
  42424. * This helps controlling the emissive effect without modifying the emissive color.
  42425. */
  42426. _this.emissiveIntensity = 1.0;
  42427. /**
  42428. * Intensity of the environment e.g. how much the environment will light the object
  42429. * either through harmonics for rough material or through the refelction for shiny ones.
  42430. */
  42431. _this.environmentIntensity = 1.0;
  42432. /**
  42433. * This is a special control allowing the reduction of the specular highlights coming from the
  42434. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42435. */
  42436. _this.specularIntensity = 1.0;
  42437. /**
  42438. * Debug Control allowing disabling the bump map on this material.
  42439. */
  42440. _this.disableBumpMap = false;
  42441. /**
  42442. * AKA Occlusion Texture Intensity in other nomenclature.
  42443. */
  42444. _this.ambientTextureStrength = 1.0;
  42445. /**
  42446. * The color of a material in ambient lighting.
  42447. */
  42448. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42449. /**
  42450. * AKA Diffuse Color in other nomenclature.
  42451. */
  42452. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42453. /**
  42454. * AKA Specular Color in other nomenclature.
  42455. */
  42456. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42457. /**
  42458. * The color reflected from the material.
  42459. */
  42460. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42461. /**
  42462. * The color emitted from the material.
  42463. */
  42464. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42465. /**
  42466. * AKA Glossiness in other nomenclature.
  42467. */
  42468. _this.microSurface = 1.0;
  42469. /**
  42470. * source material index of refraction (IOR)' / 'destination material IOR.
  42471. */
  42472. _this.indexOfRefraction = 0.66;
  42473. /**
  42474. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42475. */
  42476. _this.invertRefractionY = false;
  42477. /**
  42478. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42479. * Materials half opaque for instance using refraction could benefit from this control.
  42480. */
  42481. _this.linkRefractionWithTransparency = false;
  42482. _this.useLightmapAsShadowmap = false;
  42483. /**
  42484. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42485. */
  42486. _this.useAlphaFromAlbedoTexture = false;
  42487. /**
  42488. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42489. */
  42490. _this.forceAlphaTest = false;
  42491. /**
  42492. * Defines the alpha limits in alpha test mode.
  42493. */
  42494. _this.alphaCutOff = 0.4;
  42495. /**
  42496. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42497. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42498. */
  42499. _this.useSpecularOverAlpha = true;
  42500. /**
  42501. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42502. */
  42503. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42504. /**
  42505. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42506. */
  42507. _this.useRoughnessFromMetallicTextureAlpha = true;
  42508. /**
  42509. * Specifies if the metallic texture contains the roughness information in its green channel.
  42510. */
  42511. _this.useRoughnessFromMetallicTextureGreen = false;
  42512. /**
  42513. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42514. */
  42515. _this.useMetallnessFromMetallicTextureBlue = false;
  42516. /**
  42517. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42518. */
  42519. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42520. /**
  42521. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42522. */
  42523. _this.useAmbientInGrayScale = false;
  42524. /**
  42525. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42526. * The material will try to infer what glossiness each pixel should be.
  42527. */
  42528. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42529. /**
  42530. * BJS is using an harcoded light falloff based on a manually sets up range.
  42531. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42532. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42533. */
  42534. _this.usePhysicalLightFalloff = true;
  42535. /**
  42536. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42537. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42538. */
  42539. _this.useRadianceOverAlpha = true;
  42540. /**
  42541. * Allows using an object space normal map (instead of tangent space).
  42542. */
  42543. _this.useObjectSpaceNormalMap = false;
  42544. /**
  42545. * Allows using the bump map in parallax mode.
  42546. */
  42547. _this.useParallax = false;
  42548. /**
  42549. * Allows using the bump map in parallax occlusion mode.
  42550. */
  42551. _this.useParallaxOcclusion = false;
  42552. /**
  42553. * Controls the scale bias of the parallax mode.
  42554. */
  42555. _this.parallaxScaleBias = 0.05;
  42556. /**
  42557. * If sets to true, disables all the lights affecting the material.
  42558. */
  42559. _this.disableLighting = false;
  42560. /**
  42561. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42562. */
  42563. _this.forceIrradianceInFragment = false;
  42564. /**
  42565. * Number of Simultaneous lights allowed on the material.
  42566. */
  42567. _this.maxSimultaneousLights = 4;
  42568. /**
  42569. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42570. */
  42571. _this.invertNormalMapX = false;
  42572. /**
  42573. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42574. */
  42575. _this.invertNormalMapY = false;
  42576. /**
  42577. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42578. */
  42579. _this.twoSidedLighting = false;
  42580. /**
  42581. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42582. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42583. */
  42584. _this.useAlphaFresnel = false;
  42585. /**
  42586. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42587. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42588. */
  42589. _this.useLinearAlphaFresnel = false;
  42590. /**
  42591. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42592. * And/Or occlude the blended part.
  42593. */
  42594. _this.environmentBRDFTexture = null;
  42595. /**
  42596. * Force normal to face away from face.
  42597. */
  42598. _this.forceNormalForward = false;
  42599. /**
  42600. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42601. * makes the reflect vector face the model (under horizon).
  42602. */
  42603. _this.useHorizonOcclusion = true;
  42604. /**
  42605. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42606. * too much the area relying on ambient texture to define their ambient occlusion.
  42607. */
  42608. _this.useRadianceOcclusion = true;
  42609. /**
  42610. * If set to true, no lighting calculations will be applied.
  42611. */
  42612. _this.unlit = false;
  42613. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42614. return _this;
  42615. }
  42616. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42617. /**
  42618. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42619. */
  42620. get: function () {
  42621. return this._PBRMATERIAL_OPAQUE;
  42622. },
  42623. enumerable: true,
  42624. configurable: true
  42625. });
  42626. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42627. /**
  42628. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42629. */
  42630. get: function () {
  42631. return this._PBRMATERIAL_ALPHATEST;
  42632. },
  42633. enumerable: true,
  42634. configurable: true
  42635. });
  42636. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42637. /**
  42638. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42639. */
  42640. get: function () {
  42641. return this._PBRMATERIAL_ALPHABLEND;
  42642. },
  42643. enumerable: true,
  42644. configurable: true
  42645. });
  42646. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42647. /**
  42648. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42649. * They are also discarded below the alpha cutoff threshold to improve performances.
  42650. */
  42651. get: function () {
  42652. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42653. },
  42654. enumerable: true,
  42655. configurable: true
  42656. });
  42657. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42658. /**
  42659. * Gets the image processing configuration used either in this material.
  42660. */
  42661. get: function () {
  42662. return this._imageProcessingConfiguration;
  42663. },
  42664. /**
  42665. * Sets the Default image processing configuration used either in the this material.
  42666. *
  42667. * If sets to null, the scene one is in use.
  42668. */
  42669. set: function (value) {
  42670. this._attachImageProcessingConfiguration(value);
  42671. // Ensure the effect will be rebuilt.
  42672. this._markAllSubMeshesAsTexturesDirty();
  42673. },
  42674. enumerable: true,
  42675. configurable: true
  42676. });
  42677. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42678. /**
  42679. * Gets wether the color curves effect is enabled.
  42680. */
  42681. get: function () {
  42682. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42683. },
  42684. /**
  42685. * Sets wether the color curves effect is enabled.
  42686. */
  42687. set: function (value) {
  42688. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42689. },
  42690. enumerable: true,
  42691. configurable: true
  42692. });
  42693. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42694. /**
  42695. * Gets wether the color grading effect is enabled.
  42696. */
  42697. get: function () {
  42698. return this.imageProcessingConfiguration.colorGradingEnabled;
  42699. },
  42700. /**
  42701. * Gets wether the color grading effect is enabled.
  42702. */
  42703. set: function (value) {
  42704. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42705. },
  42706. enumerable: true,
  42707. configurable: true
  42708. });
  42709. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42710. /**
  42711. * Gets wether tonemapping is enabled or not.
  42712. */
  42713. get: function () {
  42714. return this._imageProcessingConfiguration.toneMappingEnabled;
  42715. },
  42716. /**
  42717. * Sets wether tonemapping is enabled or not
  42718. */
  42719. set: function (value) {
  42720. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42721. },
  42722. enumerable: true,
  42723. configurable: true
  42724. });
  42725. ;
  42726. ;
  42727. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42728. /**
  42729. * The camera exposure used on this material.
  42730. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42731. * This corresponds to a photographic exposure.
  42732. */
  42733. get: function () {
  42734. return this._imageProcessingConfiguration.exposure;
  42735. },
  42736. /**
  42737. * The camera exposure used on this material.
  42738. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42739. * This corresponds to a photographic exposure.
  42740. */
  42741. set: function (value) {
  42742. this._imageProcessingConfiguration.exposure = value;
  42743. },
  42744. enumerable: true,
  42745. configurable: true
  42746. });
  42747. ;
  42748. ;
  42749. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42750. /**
  42751. * Gets The camera contrast used on this material.
  42752. */
  42753. get: function () {
  42754. return this._imageProcessingConfiguration.contrast;
  42755. },
  42756. /**
  42757. * Sets The camera contrast used on this material.
  42758. */
  42759. set: function (value) {
  42760. this._imageProcessingConfiguration.contrast = value;
  42761. },
  42762. enumerable: true,
  42763. configurable: true
  42764. });
  42765. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42766. /**
  42767. * Gets the Color Grading 2D Lookup Texture.
  42768. */
  42769. get: function () {
  42770. return this._imageProcessingConfiguration.colorGradingTexture;
  42771. },
  42772. /**
  42773. * Sets the Color Grading 2D Lookup Texture.
  42774. */
  42775. set: function (value) {
  42776. this._imageProcessingConfiguration.colorGradingTexture = value;
  42777. },
  42778. enumerable: true,
  42779. configurable: true
  42780. });
  42781. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42782. /**
  42783. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42784. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42785. * 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;
  42786. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42787. */
  42788. get: function () {
  42789. return this._imageProcessingConfiguration.colorCurves;
  42790. },
  42791. /**
  42792. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42793. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42794. * 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;
  42795. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42796. */
  42797. set: function (value) {
  42798. this._imageProcessingConfiguration.colorCurves = value;
  42799. },
  42800. enumerable: true,
  42801. configurable: true
  42802. });
  42803. /**
  42804. * Returns the name of this material class.
  42805. */
  42806. PBRMaterial.prototype.getClassName = function () {
  42807. return "PBRMaterial";
  42808. };
  42809. /**
  42810. * Returns an array of the actively used textures.
  42811. * @returns - Array of BaseTextures
  42812. */
  42813. PBRMaterial.prototype.getActiveTextures = function () {
  42814. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42815. if (this._albedoTexture) {
  42816. activeTextures.push(this._albedoTexture);
  42817. }
  42818. if (this._ambientTexture) {
  42819. activeTextures.push(this._ambientTexture);
  42820. }
  42821. if (this._opacityTexture) {
  42822. activeTextures.push(this._opacityTexture);
  42823. }
  42824. if (this._reflectionTexture) {
  42825. activeTextures.push(this._reflectionTexture);
  42826. }
  42827. if (this._emissiveTexture) {
  42828. activeTextures.push(this._emissiveTexture);
  42829. }
  42830. if (this._reflectivityTexture) {
  42831. activeTextures.push(this._reflectivityTexture);
  42832. }
  42833. if (this._metallicTexture) {
  42834. activeTextures.push(this._metallicTexture);
  42835. }
  42836. if (this._microSurfaceTexture) {
  42837. activeTextures.push(this._microSurfaceTexture);
  42838. }
  42839. if (this._bumpTexture) {
  42840. activeTextures.push(this._bumpTexture);
  42841. }
  42842. if (this._lightmapTexture) {
  42843. activeTextures.push(this._lightmapTexture);
  42844. }
  42845. if (this._refractionTexture) {
  42846. activeTextures.push(this._refractionTexture);
  42847. }
  42848. return activeTextures;
  42849. };
  42850. /**
  42851. * Checks to see if a texture is used in the material.
  42852. * @param texture - Base texture to use.
  42853. * @returns - Boolean specifying if a texture is used in the material.
  42854. */
  42855. PBRMaterial.prototype.hasTexture = function (texture) {
  42856. if (_super.prototype.hasTexture.call(this, texture)) {
  42857. return true;
  42858. }
  42859. if (this._albedoTexture === texture) {
  42860. return true;
  42861. }
  42862. if (this._ambientTexture === texture) {
  42863. return true;
  42864. }
  42865. if (this._opacityTexture === texture) {
  42866. return true;
  42867. }
  42868. if (this._reflectionTexture === texture) {
  42869. return true;
  42870. }
  42871. if (this._reflectivityTexture === texture) {
  42872. return true;
  42873. }
  42874. if (this._metallicTexture === texture) {
  42875. return true;
  42876. }
  42877. if (this._microSurfaceTexture === texture) {
  42878. return true;
  42879. }
  42880. if (this._bumpTexture === texture) {
  42881. return true;
  42882. }
  42883. if (this._lightmapTexture === texture) {
  42884. return true;
  42885. }
  42886. if (this._refractionTexture === texture) {
  42887. return true;
  42888. }
  42889. return false;
  42890. };
  42891. /**
  42892. * Makes a duplicate of the current material.
  42893. * @param name - name to use for the new material.
  42894. */
  42895. PBRMaterial.prototype.clone = function (name) {
  42896. var _this = this;
  42897. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42898. clone.id = name;
  42899. clone.name = name;
  42900. return clone;
  42901. };
  42902. /**
  42903. * Serializes this PBR Material.
  42904. * @returns - An object with the serialized material.
  42905. */
  42906. PBRMaterial.prototype.serialize = function () {
  42907. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42908. serializationObject.customType = "BABYLON.PBRMaterial";
  42909. return serializationObject;
  42910. };
  42911. // Statics
  42912. /**
  42913. * Parses a PBR Material from a serialized object.
  42914. * @param source - Serialized object.
  42915. * @param scene - BJS scene instance.
  42916. * @param rootUrl - url for the scene object
  42917. * @returns - PBRMaterial
  42918. */
  42919. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42920. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42921. };
  42922. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42923. /**
  42924. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42925. */
  42926. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42927. /**
  42928. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42929. */
  42930. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42931. /**
  42932. * 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.
  42933. * They are also discarded below the alpha cutoff threshold to improve performances.
  42934. */
  42935. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42936. __decorate([
  42937. BABYLON.serialize(),
  42938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42939. ], PBRMaterial.prototype, "directIntensity", void 0);
  42940. __decorate([
  42941. BABYLON.serialize(),
  42942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42943. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42944. __decorate([
  42945. BABYLON.serialize(),
  42946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42947. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42948. __decorate([
  42949. BABYLON.serialize(),
  42950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42951. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42952. __decorate([
  42953. BABYLON.serialize(),
  42954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42955. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42956. __decorate([
  42957. BABYLON.serializeAsTexture(),
  42958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42959. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42960. __decorate([
  42961. BABYLON.serializeAsTexture(),
  42962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42963. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42964. __decorate([
  42965. BABYLON.serialize(),
  42966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42967. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42968. __decorate([
  42969. BABYLON.serializeAsTexture(),
  42970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42971. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42972. __decorate([
  42973. BABYLON.serializeAsTexture(),
  42974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42975. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42976. __decorate([
  42977. BABYLON.serializeAsTexture(),
  42978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42979. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42980. __decorate([
  42981. BABYLON.serializeAsTexture(),
  42982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42983. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42984. __decorate([
  42985. BABYLON.serializeAsTexture(),
  42986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42987. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42988. __decorate([
  42989. BABYLON.serialize(),
  42990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42991. ], PBRMaterial.prototype, "metallic", void 0);
  42992. __decorate([
  42993. BABYLON.serialize(),
  42994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42995. ], PBRMaterial.prototype, "roughness", void 0);
  42996. __decorate([
  42997. BABYLON.serializeAsTexture(),
  42998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42999. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43000. __decorate([
  43001. BABYLON.serializeAsTexture(),
  43002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43003. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43004. __decorate([
  43005. BABYLON.serializeAsTexture(),
  43006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43007. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43008. __decorate([
  43009. BABYLON.serializeAsTexture(),
  43010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43011. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43012. __decorate([
  43013. BABYLON.serializeAsColor3("ambient"),
  43014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43015. ], PBRMaterial.prototype, "ambientColor", void 0);
  43016. __decorate([
  43017. BABYLON.serializeAsColor3("albedo"),
  43018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43019. ], PBRMaterial.prototype, "albedoColor", void 0);
  43020. __decorate([
  43021. BABYLON.serializeAsColor3("reflectivity"),
  43022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43023. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43024. __decorate([
  43025. BABYLON.serializeAsColor3("reflection"),
  43026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43027. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43028. __decorate([
  43029. BABYLON.serializeAsColor3("emissive"),
  43030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43031. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43032. __decorate([
  43033. BABYLON.serialize(),
  43034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43035. ], PBRMaterial.prototype, "microSurface", void 0);
  43036. __decorate([
  43037. BABYLON.serialize(),
  43038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43039. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43040. __decorate([
  43041. BABYLON.serialize(),
  43042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43043. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43044. __decorate([
  43045. BABYLON.serialize(),
  43046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43047. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43048. __decorate([
  43049. BABYLON.serialize(),
  43050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43051. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43052. __decorate([
  43053. BABYLON.serialize(),
  43054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43055. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43056. __decorate([
  43057. BABYLON.serialize(),
  43058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43059. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43060. __decorate([
  43061. BABYLON.serialize(),
  43062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43063. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43064. __decorate([
  43065. BABYLON.serialize(),
  43066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43067. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43068. __decorate([
  43069. BABYLON.serialize(),
  43070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43071. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43072. __decorate([
  43073. BABYLON.serialize(),
  43074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43075. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43076. __decorate([
  43077. BABYLON.serialize(),
  43078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43079. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43080. __decorate([
  43081. BABYLON.serialize(),
  43082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43083. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43084. __decorate([
  43085. BABYLON.serialize(),
  43086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43087. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43088. __decorate([
  43089. BABYLON.serialize(),
  43090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43091. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43092. __decorate([
  43093. BABYLON.serialize(),
  43094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43095. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43096. __decorate([
  43097. BABYLON.serialize(),
  43098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43099. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43100. __decorate([
  43101. BABYLON.serialize(),
  43102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43103. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43104. __decorate([
  43105. BABYLON.serialize(),
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43108. __decorate([
  43109. BABYLON.serialize(),
  43110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43111. ], PBRMaterial.prototype, "useParallax", void 0);
  43112. __decorate([
  43113. BABYLON.serialize(),
  43114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43115. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43116. __decorate([
  43117. BABYLON.serialize(),
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43119. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43120. __decorate([
  43121. BABYLON.serialize(),
  43122. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43123. ], PBRMaterial.prototype, "disableLighting", void 0);
  43124. __decorate([
  43125. BABYLON.serialize(),
  43126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43127. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43128. __decorate([
  43129. BABYLON.serialize(),
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43131. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43132. __decorate([
  43133. BABYLON.serialize(),
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43136. __decorate([
  43137. BABYLON.serialize(),
  43138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43139. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43140. __decorate([
  43141. BABYLON.serialize(),
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43144. __decorate([
  43145. BABYLON.serialize(),
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43148. __decorate([
  43149. BABYLON.serialize(),
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43151. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43152. __decorate([
  43153. BABYLON.serializeAsTexture(),
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43155. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43156. __decorate([
  43157. BABYLON.serialize(),
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43159. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43160. __decorate([
  43161. BABYLON.serialize(),
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43163. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43164. __decorate([
  43165. BABYLON.serialize(),
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43168. __decorate([
  43169. BABYLON.serialize(),
  43170. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43171. ], PBRMaterial.prototype, "unlit", void 0);
  43172. return PBRMaterial;
  43173. }(BABYLON.PBRBaseMaterial));
  43174. BABYLON.PBRMaterial = PBRMaterial;
  43175. })(BABYLON || (BABYLON = {}));
  43176. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43177. "use strict";
  43178. var BABYLON;
  43179. (function (BABYLON) {
  43180. /**
  43181. * The PBR material of BJS following the metal roughness convention.
  43182. *
  43183. * This fits to the PBR convention in the GLTF definition:
  43184. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43185. */
  43186. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43187. __extends(PBRMetallicRoughnessMaterial, _super);
  43188. /**
  43189. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43190. *
  43191. * @param name The material name
  43192. * @param scene The scene the material will be use in.
  43193. */
  43194. function PBRMetallicRoughnessMaterial(name, scene) {
  43195. var _this = _super.call(this, name, scene) || this;
  43196. _this._useRoughnessFromMetallicTextureAlpha = false;
  43197. _this._useRoughnessFromMetallicTextureGreen = true;
  43198. _this._useMetallnessFromMetallicTextureBlue = true;
  43199. _this.metallic = 1.0;
  43200. _this.roughness = 1.0;
  43201. return _this;
  43202. }
  43203. /**
  43204. * Return the currrent class name of the material.
  43205. */
  43206. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43207. return "PBRMetallicRoughnessMaterial";
  43208. };
  43209. /**
  43210. * Return the active textures of the material.
  43211. */
  43212. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43213. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43214. if (this.baseTexture) {
  43215. activeTextures.push(this.baseTexture);
  43216. }
  43217. if (this.metallicRoughnessTexture) {
  43218. activeTextures.push(this.metallicRoughnessTexture);
  43219. }
  43220. return activeTextures;
  43221. };
  43222. /**
  43223. * Checks to see if a texture is used in the material.
  43224. * @param texture - Base texture to use.
  43225. * @returns - Boolean specifying if a texture is used in the material.
  43226. */
  43227. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43228. if (_super.prototype.hasTexture.call(this, texture)) {
  43229. return true;
  43230. }
  43231. if (this.baseTexture === texture) {
  43232. return true;
  43233. }
  43234. if (this.metallicRoughnessTexture === texture) {
  43235. return true;
  43236. }
  43237. return false;
  43238. };
  43239. /**
  43240. * Makes a duplicate of the current material.
  43241. * @param name - name to use for the new material.
  43242. */
  43243. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43244. var _this = this;
  43245. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43246. clone.id = name;
  43247. clone.name = name;
  43248. return clone;
  43249. };
  43250. /**
  43251. * Serialize the material to a parsable JSON object.
  43252. */
  43253. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43254. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43255. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43256. return serializationObject;
  43257. };
  43258. /**
  43259. * Parses a JSON object correponding to the serialize function.
  43260. */
  43261. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43262. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43263. };
  43264. __decorate([
  43265. BABYLON.serializeAsColor3(),
  43266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43267. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43268. __decorate([
  43269. BABYLON.serializeAsTexture(),
  43270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43271. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43272. __decorate([
  43273. BABYLON.serialize(),
  43274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43275. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43276. __decorate([
  43277. BABYLON.serialize(),
  43278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43279. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43280. __decorate([
  43281. BABYLON.serializeAsTexture(),
  43282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43283. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43284. return PBRMetallicRoughnessMaterial;
  43285. }(BABYLON.PBRBaseSimpleMaterial));
  43286. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43287. })(BABYLON || (BABYLON = {}));
  43288. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43289. "use strict";
  43290. var BABYLON;
  43291. (function (BABYLON) {
  43292. /**
  43293. * The PBR material of BJS following the specular glossiness convention.
  43294. *
  43295. * This fits to the PBR convention in the GLTF definition:
  43296. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43297. */
  43298. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43299. __extends(PBRSpecularGlossinessMaterial, _super);
  43300. /**
  43301. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43302. *
  43303. * @param name The material name
  43304. * @param scene The scene the material will be use in.
  43305. */
  43306. function PBRSpecularGlossinessMaterial(name, scene) {
  43307. var _this = _super.call(this, name, scene) || this;
  43308. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43309. return _this;
  43310. }
  43311. /**
  43312. * Return the currrent class name of the material.
  43313. */
  43314. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43315. return "PBRSpecularGlossinessMaterial";
  43316. };
  43317. /**
  43318. * Return the active textures of the material.
  43319. */
  43320. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43321. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43322. if (this.diffuseTexture) {
  43323. activeTextures.push(this.diffuseTexture);
  43324. }
  43325. if (this.specularGlossinessTexture) {
  43326. activeTextures.push(this.specularGlossinessTexture);
  43327. }
  43328. return activeTextures;
  43329. };
  43330. /**
  43331. * Checks to see if a texture is used in the material.
  43332. * @param texture - Base texture to use.
  43333. * @returns - Boolean specifying if a texture is used in the material.
  43334. */
  43335. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43336. if (_super.prototype.hasTexture.call(this, texture)) {
  43337. return true;
  43338. }
  43339. if (this.diffuseTexture === texture) {
  43340. return true;
  43341. }
  43342. if (this.specularGlossinessTexture === texture) {
  43343. return true;
  43344. }
  43345. return false;
  43346. };
  43347. /**
  43348. * Makes a duplicate of the current material.
  43349. * @param name - name to use for the new material.
  43350. */
  43351. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43352. var _this = this;
  43353. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43354. clone.id = name;
  43355. clone.name = name;
  43356. return clone;
  43357. };
  43358. /**
  43359. * Serialize the material to a parsable JSON object.
  43360. */
  43361. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43362. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43363. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43364. return serializationObject;
  43365. };
  43366. /**
  43367. * Parses a JSON object correponding to the serialize function.
  43368. */
  43369. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43370. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43371. };
  43372. __decorate([
  43373. BABYLON.serializeAsColor3("diffuse"),
  43374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43375. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43376. __decorate([
  43377. BABYLON.serializeAsTexture(),
  43378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43379. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43380. __decorate([
  43381. BABYLON.serializeAsColor3("specular"),
  43382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43383. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43384. __decorate([
  43385. BABYLON.serialize(),
  43386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43387. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43388. __decorate([
  43389. BABYLON.serializeAsTexture(),
  43390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43391. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43392. return PBRSpecularGlossinessMaterial;
  43393. }(BABYLON.PBRBaseSimpleMaterial));
  43394. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43395. })(BABYLON || (BABYLON = {}));
  43396. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43397. "use strict";
  43398. var BABYLON;
  43399. (function (BABYLON) {
  43400. BABYLON.CameraInputTypes = {};
  43401. var CameraInputsManager = /** @class */ (function () {
  43402. function CameraInputsManager(camera) {
  43403. this.attached = {};
  43404. this.camera = camera;
  43405. this.checkInputs = function () { };
  43406. }
  43407. /**
  43408. * Add an input method to a camera.
  43409. * builtin inputs example: camera.inputs.addGamepad();
  43410. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43411. * @param input camera input method
  43412. */
  43413. CameraInputsManager.prototype.add = function (input) {
  43414. var type = input.getSimpleName();
  43415. if (this.attached[type]) {
  43416. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43417. return;
  43418. }
  43419. this.attached[type] = input;
  43420. input.camera = this.camera;
  43421. //for checkInputs, we are dynamically creating a function
  43422. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43423. if (input.checkInputs) {
  43424. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43425. }
  43426. if (this.attachedElement) {
  43427. input.attachControl(this.attachedElement);
  43428. }
  43429. };
  43430. /**
  43431. * Remove a specific input method from a camera
  43432. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43433. * @param inputToRemove camera input method
  43434. */
  43435. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43436. for (var cam in this.attached) {
  43437. var input = this.attached[cam];
  43438. if (input === inputToRemove) {
  43439. input.detachControl(this.attachedElement);
  43440. input.camera = null;
  43441. delete this.attached[cam];
  43442. this.rebuildInputCheck();
  43443. }
  43444. }
  43445. };
  43446. CameraInputsManager.prototype.removeByType = function (inputType) {
  43447. for (var cam in this.attached) {
  43448. var input = this.attached[cam];
  43449. if (input.getClassName() === inputType) {
  43450. input.detachControl(this.attachedElement);
  43451. input.camera = null;
  43452. delete this.attached[cam];
  43453. this.rebuildInputCheck();
  43454. }
  43455. }
  43456. };
  43457. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43458. var current = this.checkInputs;
  43459. return function () {
  43460. current();
  43461. fn();
  43462. };
  43463. };
  43464. CameraInputsManager.prototype.attachInput = function (input) {
  43465. if (this.attachedElement) {
  43466. input.attachControl(this.attachedElement, this.noPreventDefault);
  43467. }
  43468. };
  43469. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43470. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43471. if (this.attachedElement) {
  43472. return;
  43473. }
  43474. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43475. this.attachedElement = element;
  43476. this.noPreventDefault = noPreventDefault;
  43477. for (var cam in this.attached) {
  43478. this.attached[cam].attachControl(element, noPreventDefault);
  43479. }
  43480. };
  43481. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43482. if (disconnect === void 0) { disconnect = false; }
  43483. if (this.attachedElement !== element) {
  43484. return;
  43485. }
  43486. for (var cam in this.attached) {
  43487. this.attached[cam].detachControl(element);
  43488. if (disconnect) {
  43489. this.attached[cam].camera = null;
  43490. }
  43491. }
  43492. this.attachedElement = null;
  43493. };
  43494. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43495. this.checkInputs = function () { };
  43496. for (var cam in this.attached) {
  43497. var input = this.attached[cam];
  43498. if (input.checkInputs) {
  43499. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43500. }
  43501. }
  43502. };
  43503. /**
  43504. * Remove all attached input methods from a camera
  43505. */
  43506. CameraInputsManager.prototype.clear = function () {
  43507. if (this.attachedElement) {
  43508. this.detachElement(this.attachedElement, true);
  43509. }
  43510. this.attached = {};
  43511. this.attachedElement = null;
  43512. this.checkInputs = function () { };
  43513. };
  43514. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43515. var inputs = {};
  43516. for (var cam in this.attached) {
  43517. var input = this.attached[cam];
  43518. var res = BABYLON.SerializationHelper.Serialize(input);
  43519. inputs[input.getClassName()] = res;
  43520. }
  43521. serializedCamera.inputsmgr = inputs;
  43522. };
  43523. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43524. var parsedInputs = parsedCamera.inputsmgr;
  43525. if (parsedInputs) {
  43526. this.clear();
  43527. for (var n in parsedInputs) {
  43528. var construct = BABYLON.CameraInputTypes[n];
  43529. if (construct) {
  43530. var parsedinput = parsedInputs[n];
  43531. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43532. this.add(input);
  43533. }
  43534. }
  43535. }
  43536. else {
  43537. //2016-03-08 this part is for managing backward compatibility
  43538. for (var n in this.attached) {
  43539. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43540. if (construct) {
  43541. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43542. this.remove(this.attached[n]);
  43543. this.add(input);
  43544. }
  43545. }
  43546. }
  43547. };
  43548. return CameraInputsManager;
  43549. }());
  43550. BABYLON.CameraInputsManager = CameraInputsManager;
  43551. })(BABYLON || (BABYLON = {}));
  43552. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43553. "use strict";
  43554. var BABYLON;
  43555. (function (BABYLON) {
  43556. var TargetCamera = /** @class */ (function (_super) {
  43557. __extends(TargetCamera, _super);
  43558. function TargetCamera(name, position, scene) {
  43559. var _this = _super.call(this, name, position, scene) || this;
  43560. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43561. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43562. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43563. _this.speed = 2.0;
  43564. _this.noRotationConstraint = false;
  43565. _this.lockedTarget = null;
  43566. _this._currentTarget = BABYLON.Vector3.Zero();
  43567. _this._viewMatrix = BABYLON.Matrix.Zero();
  43568. _this._camMatrix = BABYLON.Matrix.Zero();
  43569. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43570. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43571. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43572. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43573. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43574. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43575. _this._tempMatrix = BABYLON.Matrix.Zero();
  43576. return _this;
  43577. }
  43578. TargetCamera.prototype.getFrontPosition = function (distance) {
  43579. this.getWorldMatrix();
  43580. var direction = this.getTarget().subtract(this.position);
  43581. direction.normalize();
  43582. direction.scaleInPlace(distance);
  43583. return this.globalPosition.add(direction);
  43584. };
  43585. TargetCamera.prototype._getLockedTargetPosition = function () {
  43586. if (!this.lockedTarget) {
  43587. return null;
  43588. }
  43589. if (this.lockedTarget.absolutePosition) {
  43590. this.lockedTarget.computeWorldMatrix();
  43591. }
  43592. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43593. };
  43594. TargetCamera.prototype.storeState = function () {
  43595. this._storedPosition = this.position.clone();
  43596. this._storedRotation = this.rotation.clone();
  43597. if (this.rotationQuaternion) {
  43598. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43599. }
  43600. return _super.prototype.storeState.call(this);
  43601. };
  43602. /**
  43603. * Restored camera state. You must call storeState() first
  43604. */
  43605. TargetCamera.prototype._restoreStateValues = function () {
  43606. if (!_super.prototype._restoreStateValues.call(this)) {
  43607. return false;
  43608. }
  43609. this.position = this._storedPosition.clone();
  43610. this.rotation = this._storedRotation.clone();
  43611. if (this.rotationQuaternion) {
  43612. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43613. }
  43614. this.cameraDirection.copyFromFloats(0, 0, 0);
  43615. this.cameraRotation.copyFromFloats(0, 0);
  43616. return true;
  43617. };
  43618. // Cache
  43619. TargetCamera.prototype._initCache = function () {
  43620. _super.prototype._initCache.call(this);
  43621. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43622. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43623. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43624. };
  43625. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43626. if (!ignoreParentClass) {
  43627. _super.prototype._updateCache.call(this);
  43628. }
  43629. var lockedTargetPosition = this._getLockedTargetPosition();
  43630. if (!lockedTargetPosition) {
  43631. this._cache.lockedTarget = null;
  43632. }
  43633. else {
  43634. if (!this._cache.lockedTarget) {
  43635. this._cache.lockedTarget = lockedTargetPosition.clone();
  43636. }
  43637. else {
  43638. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43639. }
  43640. }
  43641. this._cache.rotation.copyFrom(this.rotation);
  43642. if (this.rotationQuaternion)
  43643. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43644. };
  43645. // Synchronized
  43646. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43647. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43648. return false;
  43649. }
  43650. var lockedTargetPosition = this._getLockedTargetPosition();
  43651. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43652. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43653. };
  43654. // Methods
  43655. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43656. var engine = this.getEngine();
  43657. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43658. };
  43659. // Target
  43660. TargetCamera.prototype.setTarget = function (target) {
  43661. this.upVector.normalize();
  43662. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43663. this._camMatrix.invert();
  43664. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43665. var vDir = target.subtract(this.position);
  43666. if (vDir.x >= 0.0) {
  43667. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43668. }
  43669. else {
  43670. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43671. }
  43672. this.rotation.z = 0;
  43673. if (isNaN(this.rotation.x)) {
  43674. this.rotation.x = 0;
  43675. }
  43676. if (isNaN(this.rotation.y)) {
  43677. this.rotation.y = 0;
  43678. }
  43679. if (isNaN(this.rotation.z)) {
  43680. this.rotation.z = 0;
  43681. }
  43682. if (this.rotationQuaternion) {
  43683. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43684. }
  43685. };
  43686. /**
  43687. * Return the current target position of the camera. This value is expressed in local space.
  43688. */
  43689. TargetCamera.prototype.getTarget = function () {
  43690. return this._currentTarget;
  43691. };
  43692. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43693. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43694. };
  43695. TargetCamera.prototype._updatePosition = function () {
  43696. if (this.parent) {
  43697. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43698. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43699. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43700. return;
  43701. }
  43702. this.position.addInPlace(this.cameraDirection);
  43703. };
  43704. TargetCamera.prototype._checkInputs = function () {
  43705. var needToMove = this._decideIfNeedsToMove();
  43706. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43707. // Move
  43708. if (needToMove) {
  43709. this._updatePosition();
  43710. }
  43711. // Rotate
  43712. if (needToRotate) {
  43713. this.rotation.x += this.cameraRotation.x;
  43714. this.rotation.y += this.cameraRotation.y;
  43715. //rotate, if quaternion is set and rotation was used
  43716. if (this.rotationQuaternion) {
  43717. var len = this.rotation.lengthSquared();
  43718. if (len) {
  43719. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43720. }
  43721. }
  43722. if (!this.noRotationConstraint) {
  43723. var limit = (Math.PI / 2) * 0.95;
  43724. if (this.rotation.x > limit)
  43725. this.rotation.x = limit;
  43726. if (this.rotation.x < -limit)
  43727. this.rotation.x = -limit;
  43728. }
  43729. }
  43730. // Inertia
  43731. if (needToMove) {
  43732. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43733. this.cameraDirection.x = 0;
  43734. }
  43735. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43736. this.cameraDirection.y = 0;
  43737. }
  43738. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43739. this.cameraDirection.z = 0;
  43740. }
  43741. this.cameraDirection.scaleInPlace(this.inertia);
  43742. }
  43743. if (needToRotate) {
  43744. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43745. this.cameraRotation.x = 0;
  43746. }
  43747. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43748. this.cameraRotation.y = 0;
  43749. }
  43750. this.cameraRotation.scaleInPlace(this.inertia);
  43751. }
  43752. _super.prototype._checkInputs.call(this);
  43753. };
  43754. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43755. if (this.rotationQuaternion) {
  43756. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43757. }
  43758. else {
  43759. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43760. }
  43761. //update the up vector!
  43762. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43763. };
  43764. TargetCamera.prototype._getViewMatrix = function () {
  43765. if (this.lockedTarget) {
  43766. this.setTarget(this._getLockedTargetPosition());
  43767. }
  43768. // Compute
  43769. this._updateCameraRotationMatrix();
  43770. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43771. // Computing target and final matrix
  43772. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43773. if (this.getScene().useRightHandedSystem) {
  43774. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43775. }
  43776. else {
  43777. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43778. }
  43779. return this._viewMatrix;
  43780. };
  43781. /**
  43782. * @override
  43783. * Override Camera.createRigCamera
  43784. */
  43785. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43786. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43787. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43788. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43789. if (!this.rotationQuaternion) {
  43790. this.rotationQuaternion = new BABYLON.Quaternion();
  43791. }
  43792. rigCamera._cameraRigParams = {};
  43793. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43794. }
  43795. return rigCamera;
  43796. }
  43797. return null;
  43798. };
  43799. /**
  43800. * @override
  43801. * Override Camera._updateRigCameras
  43802. */
  43803. TargetCamera.prototype._updateRigCameras = function () {
  43804. var camLeft = this._rigCameras[0];
  43805. var camRight = this._rigCameras[1];
  43806. switch (this.cameraRigMode) {
  43807. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43808. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43809. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43810. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43811. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43812. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43813. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43814. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43815. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43816. camLeft.setTarget(this.getTarget());
  43817. camRight.setTarget(this.getTarget());
  43818. break;
  43819. case BABYLON.Camera.RIG_MODE_VR:
  43820. if (camLeft.rotationQuaternion) {
  43821. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43822. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43823. }
  43824. else {
  43825. camLeft.rotation.copyFrom(this.rotation);
  43826. camRight.rotation.copyFrom(this.rotation);
  43827. }
  43828. camLeft.position.copyFrom(this.position);
  43829. camRight.position.copyFrom(this.position);
  43830. break;
  43831. }
  43832. _super.prototype._updateRigCameras.call(this);
  43833. };
  43834. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43835. if (!this._rigCamTransformMatrix) {
  43836. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43837. }
  43838. var target = this.getTarget();
  43839. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43840. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43841. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43842. };
  43843. TargetCamera.prototype.getClassName = function () {
  43844. return "TargetCamera";
  43845. };
  43846. __decorate([
  43847. BABYLON.serializeAsVector3()
  43848. ], TargetCamera.prototype, "rotation", void 0);
  43849. __decorate([
  43850. BABYLON.serialize()
  43851. ], TargetCamera.prototype, "speed", void 0);
  43852. __decorate([
  43853. BABYLON.serializeAsMeshReference("lockedTargetId")
  43854. ], TargetCamera.prototype, "lockedTarget", void 0);
  43855. return TargetCamera;
  43856. }(BABYLON.Camera));
  43857. BABYLON.TargetCamera = TargetCamera;
  43858. })(BABYLON || (BABYLON = {}));
  43859. //# sourceMappingURL=babylon.targetCamera.js.map
  43860. "use strict";
  43861. var BABYLON;
  43862. (function (BABYLON) {
  43863. var FreeCameraMouseInput = /** @class */ (function () {
  43864. function FreeCameraMouseInput(touchEnabled) {
  43865. if (touchEnabled === void 0) { touchEnabled = true; }
  43866. this.touchEnabled = touchEnabled;
  43867. this.buttons = [0, 1, 2];
  43868. this.angularSensibility = 2000.0;
  43869. this.previousPosition = null;
  43870. }
  43871. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43872. var _this = this;
  43873. var engine = this.camera.getEngine();
  43874. if (!this._pointerInput) {
  43875. this._pointerInput = function (p, s) {
  43876. var evt = p.event;
  43877. if (engine.isInVRExclusivePointerMode) {
  43878. return;
  43879. }
  43880. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43881. return;
  43882. }
  43883. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43884. return;
  43885. }
  43886. var srcElement = (evt.srcElement || evt.target);
  43887. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43888. try {
  43889. srcElement.setPointerCapture(evt.pointerId);
  43890. }
  43891. catch (e) {
  43892. //Nothing to do with the error. Execution will continue.
  43893. }
  43894. _this.previousPosition = {
  43895. x: evt.clientX,
  43896. y: evt.clientY
  43897. };
  43898. if (!noPreventDefault) {
  43899. evt.preventDefault();
  43900. element.focus();
  43901. }
  43902. }
  43903. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43904. try {
  43905. srcElement.releasePointerCapture(evt.pointerId);
  43906. }
  43907. catch (e) {
  43908. //Nothing to do with the error.
  43909. }
  43910. _this.previousPosition = null;
  43911. if (!noPreventDefault) {
  43912. evt.preventDefault();
  43913. }
  43914. }
  43915. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43916. if (!_this.previousPosition || engine.isPointerLock) {
  43917. return;
  43918. }
  43919. var offsetX = evt.clientX - _this.previousPosition.x;
  43920. var offsetY = evt.clientY - _this.previousPosition.y;
  43921. if (_this.camera.getScene().useRightHandedSystem) {
  43922. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43923. }
  43924. else {
  43925. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43926. }
  43927. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43928. _this.previousPosition = {
  43929. x: evt.clientX,
  43930. y: evt.clientY
  43931. };
  43932. if (!noPreventDefault) {
  43933. evt.preventDefault();
  43934. }
  43935. }
  43936. };
  43937. }
  43938. this._onMouseMove = function (evt) {
  43939. if (!engine.isPointerLock) {
  43940. return;
  43941. }
  43942. if (engine.isInVRExclusivePointerMode) {
  43943. return;
  43944. }
  43945. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43946. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43947. if (_this.camera.getScene().useRightHandedSystem) {
  43948. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43949. }
  43950. else {
  43951. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43952. }
  43953. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43954. _this.previousPosition = null;
  43955. if (!noPreventDefault) {
  43956. evt.preventDefault();
  43957. }
  43958. };
  43959. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43960. element.addEventListener("mousemove", this._onMouseMove, false);
  43961. };
  43962. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43963. if (this._observer && element) {
  43964. this.camera.getScene().onPointerObservable.remove(this._observer);
  43965. if (this._onMouseMove) {
  43966. element.removeEventListener("mousemove", this._onMouseMove);
  43967. }
  43968. this._observer = null;
  43969. this._onMouseMove = null;
  43970. this.previousPosition = null;
  43971. }
  43972. };
  43973. FreeCameraMouseInput.prototype.getClassName = function () {
  43974. return "FreeCameraMouseInput";
  43975. };
  43976. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43977. return "mouse";
  43978. };
  43979. __decorate([
  43980. BABYLON.serialize()
  43981. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43982. __decorate([
  43983. BABYLON.serialize()
  43984. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43985. return FreeCameraMouseInput;
  43986. }());
  43987. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43988. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43989. })(BABYLON || (BABYLON = {}));
  43990. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43991. "use strict";
  43992. var BABYLON;
  43993. (function (BABYLON) {
  43994. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43995. function FreeCameraKeyboardMoveInput() {
  43996. this._keys = new Array();
  43997. this.keysUp = [38];
  43998. this.keysDown = [40];
  43999. this.keysLeft = [37];
  44000. this.keysRight = [39];
  44001. }
  44002. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44003. var _this = this;
  44004. if (this._onCanvasBlurObserver) {
  44005. return;
  44006. }
  44007. this._scene = this.camera.getScene();
  44008. this._engine = this._scene.getEngine();
  44009. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44010. _this._keys = [];
  44011. });
  44012. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44013. var evt = info.event;
  44014. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44015. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44016. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44017. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44018. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44019. var index = _this._keys.indexOf(evt.keyCode);
  44020. if (index === -1) {
  44021. _this._keys.push(evt.keyCode);
  44022. }
  44023. if (!noPreventDefault) {
  44024. evt.preventDefault();
  44025. }
  44026. }
  44027. }
  44028. else {
  44029. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44030. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44031. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44032. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44033. var index = _this._keys.indexOf(evt.keyCode);
  44034. if (index >= 0) {
  44035. _this._keys.splice(index, 1);
  44036. }
  44037. if (!noPreventDefault) {
  44038. evt.preventDefault();
  44039. }
  44040. }
  44041. }
  44042. });
  44043. };
  44044. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44045. if (this._scene) {
  44046. if (this._onKeyboardObserver) {
  44047. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44048. }
  44049. if (this._onCanvasBlurObserver) {
  44050. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44051. }
  44052. this._onKeyboardObserver = null;
  44053. this._onCanvasBlurObserver = null;
  44054. }
  44055. this._keys = [];
  44056. };
  44057. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44058. if (this._onKeyboardObserver) {
  44059. var camera = this.camera;
  44060. // Keyboard
  44061. for (var index = 0; index < this._keys.length; index++) {
  44062. var keyCode = this._keys[index];
  44063. var speed = camera._computeLocalCameraSpeed();
  44064. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44065. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44066. }
  44067. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44068. camera._localDirection.copyFromFloats(0, 0, speed);
  44069. }
  44070. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44071. camera._localDirection.copyFromFloats(speed, 0, 0);
  44072. }
  44073. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44074. camera._localDirection.copyFromFloats(0, 0, -speed);
  44075. }
  44076. if (camera.getScene().useRightHandedSystem) {
  44077. camera._localDirection.z *= -1;
  44078. }
  44079. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44080. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44081. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44082. }
  44083. }
  44084. };
  44085. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44086. return "FreeCameraKeyboardMoveInput";
  44087. };
  44088. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44089. this._keys = [];
  44090. };
  44091. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44092. return "keyboard";
  44093. };
  44094. __decorate([
  44095. BABYLON.serialize()
  44096. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44097. __decorate([
  44098. BABYLON.serialize()
  44099. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44100. __decorate([
  44101. BABYLON.serialize()
  44102. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44103. __decorate([
  44104. BABYLON.serialize()
  44105. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44106. return FreeCameraKeyboardMoveInput;
  44107. }());
  44108. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44109. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44110. })(BABYLON || (BABYLON = {}));
  44111. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44112. "use strict";
  44113. var BABYLON;
  44114. (function (BABYLON) {
  44115. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44116. __extends(FreeCameraInputsManager, _super);
  44117. function FreeCameraInputsManager(camera) {
  44118. return _super.call(this, camera) || this;
  44119. }
  44120. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44121. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44122. return this;
  44123. };
  44124. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44125. if (touchEnabled === void 0) { touchEnabled = true; }
  44126. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44127. return this;
  44128. };
  44129. FreeCameraInputsManager.prototype.addGamepad = function () {
  44130. this.add(new BABYLON.FreeCameraGamepadInput());
  44131. return this;
  44132. };
  44133. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44134. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44135. return this;
  44136. };
  44137. FreeCameraInputsManager.prototype.addTouch = function () {
  44138. this.add(new BABYLON.FreeCameraTouchInput());
  44139. return this;
  44140. };
  44141. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44142. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44143. return this;
  44144. };
  44145. return FreeCameraInputsManager;
  44146. }(BABYLON.CameraInputsManager));
  44147. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44148. })(BABYLON || (BABYLON = {}));
  44149. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44150. "use strict";
  44151. var BABYLON;
  44152. (function (BABYLON) {
  44153. var FreeCamera = /** @class */ (function (_super) {
  44154. __extends(FreeCamera, _super);
  44155. function FreeCamera(name, position, scene) {
  44156. var _this = _super.call(this, name, position, scene) || this;
  44157. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44158. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44159. _this.checkCollisions = false;
  44160. _this.applyGravity = false;
  44161. _this._needMoveForGravity = false;
  44162. _this._oldPosition = BABYLON.Vector3.Zero();
  44163. _this._diffPosition = BABYLON.Vector3.Zero();
  44164. _this._newPosition = BABYLON.Vector3.Zero();
  44165. // Collisions
  44166. _this._collisionMask = -1;
  44167. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44168. if (collidedMesh === void 0) { collidedMesh = null; }
  44169. //TODO move this to the collision coordinator!
  44170. if (_this.getScene().workerCollisions)
  44171. newPosition.multiplyInPlace(_this._collider._radius);
  44172. var updatePosition = function (newPos) {
  44173. _this._newPosition.copyFrom(newPos);
  44174. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44175. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44176. _this.position.addInPlace(_this._diffPosition);
  44177. if (_this.onCollide && collidedMesh) {
  44178. _this.onCollide(collidedMesh);
  44179. }
  44180. }
  44181. };
  44182. updatePosition(newPosition);
  44183. };
  44184. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44185. _this.inputs.addKeyboard().addMouse();
  44186. return _this;
  44187. }
  44188. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44189. //-- begin properties for backward compatibility for inputs
  44190. /**
  44191. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44192. * Higher values reduce sensitivity.
  44193. */
  44194. get: function () {
  44195. var mouse = this.inputs.attached["mouse"];
  44196. if (mouse)
  44197. return mouse.angularSensibility;
  44198. return 0;
  44199. },
  44200. /**
  44201. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44202. * Higher values reduce sensitivity.
  44203. */
  44204. set: function (value) {
  44205. var mouse = this.inputs.attached["mouse"];
  44206. if (mouse)
  44207. mouse.angularSensibility = value;
  44208. },
  44209. enumerable: true,
  44210. configurable: true
  44211. });
  44212. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44213. get: function () {
  44214. var keyboard = this.inputs.attached["keyboard"];
  44215. if (keyboard)
  44216. return keyboard.keysUp;
  44217. return [];
  44218. },
  44219. set: function (value) {
  44220. var keyboard = this.inputs.attached["keyboard"];
  44221. if (keyboard)
  44222. keyboard.keysUp = value;
  44223. },
  44224. enumerable: true,
  44225. configurable: true
  44226. });
  44227. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44228. get: function () {
  44229. var keyboard = this.inputs.attached["keyboard"];
  44230. if (keyboard)
  44231. return keyboard.keysDown;
  44232. return [];
  44233. },
  44234. set: function (value) {
  44235. var keyboard = this.inputs.attached["keyboard"];
  44236. if (keyboard)
  44237. keyboard.keysDown = value;
  44238. },
  44239. enumerable: true,
  44240. configurable: true
  44241. });
  44242. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44243. get: function () {
  44244. var keyboard = this.inputs.attached["keyboard"];
  44245. if (keyboard)
  44246. return keyboard.keysLeft;
  44247. return [];
  44248. },
  44249. set: function (value) {
  44250. var keyboard = this.inputs.attached["keyboard"];
  44251. if (keyboard)
  44252. keyboard.keysLeft = value;
  44253. },
  44254. enumerable: true,
  44255. configurable: true
  44256. });
  44257. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44258. get: function () {
  44259. var keyboard = this.inputs.attached["keyboard"];
  44260. if (keyboard)
  44261. return keyboard.keysRight;
  44262. return [];
  44263. },
  44264. set: function (value) {
  44265. var keyboard = this.inputs.attached["keyboard"];
  44266. if (keyboard)
  44267. keyboard.keysRight = value;
  44268. },
  44269. enumerable: true,
  44270. configurable: true
  44271. });
  44272. // Controls
  44273. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44274. this.inputs.attachElement(element, noPreventDefault);
  44275. };
  44276. FreeCamera.prototype.detachControl = function (element) {
  44277. this.inputs.detachElement(element);
  44278. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44279. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44280. };
  44281. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44282. get: function () {
  44283. return this._collisionMask;
  44284. },
  44285. set: function (mask) {
  44286. this._collisionMask = !isNaN(mask) ? mask : -1;
  44287. },
  44288. enumerable: true,
  44289. configurable: true
  44290. });
  44291. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44292. var globalPosition;
  44293. if (this.parent) {
  44294. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44295. }
  44296. else {
  44297. globalPosition = this.position;
  44298. }
  44299. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44300. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44301. if (!this._collider) {
  44302. this._collider = new BABYLON.Collider();
  44303. }
  44304. this._collider._radius = this.ellipsoid;
  44305. this._collider.collisionMask = this._collisionMask;
  44306. //no need for clone, as long as gravity is not on.
  44307. var actualDisplacement = displacement;
  44308. //add gravity to the direction to prevent the dual-collision checking
  44309. if (this.applyGravity) {
  44310. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44311. actualDisplacement = displacement.add(this.getScene().gravity);
  44312. }
  44313. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44314. };
  44315. FreeCamera.prototype._checkInputs = function () {
  44316. if (!this._localDirection) {
  44317. this._localDirection = BABYLON.Vector3.Zero();
  44318. this._transformedDirection = BABYLON.Vector3.Zero();
  44319. }
  44320. this.inputs.checkInputs();
  44321. _super.prototype._checkInputs.call(this);
  44322. };
  44323. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44324. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44325. };
  44326. FreeCamera.prototype._updatePosition = function () {
  44327. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44328. this._collideWithWorld(this.cameraDirection);
  44329. }
  44330. else {
  44331. _super.prototype._updatePosition.call(this);
  44332. }
  44333. };
  44334. FreeCamera.prototype.dispose = function () {
  44335. this.inputs.clear();
  44336. _super.prototype.dispose.call(this);
  44337. };
  44338. FreeCamera.prototype.getClassName = function () {
  44339. return "FreeCamera";
  44340. };
  44341. __decorate([
  44342. BABYLON.serializeAsVector3()
  44343. ], FreeCamera.prototype, "ellipsoid", void 0);
  44344. __decorate([
  44345. BABYLON.serializeAsVector3()
  44346. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44347. __decorate([
  44348. BABYLON.serialize()
  44349. ], FreeCamera.prototype, "checkCollisions", void 0);
  44350. __decorate([
  44351. BABYLON.serialize()
  44352. ], FreeCamera.prototype, "applyGravity", void 0);
  44353. return FreeCamera;
  44354. }(BABYLON.TargetCamera));
  44355. BABYLON.FreeCamera = FreeCamera;
  44356. })(BABYLON || (BABYLON = {}));
  44357. //# sourceMappingURL=babylon.freeCamera.js.map
  44358. "use strict";
  44359. var BABYLON;
  44360. (function (BABYLON) {
  44361. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44362. function ArcRotateCameraKeyboardMoveInput() {
  44363. this._keys = new Array();
  44364. this.keysUp = [38];
  44365. this.keysDown = [40];
  44366. this.keysLeft = [37];
  44367. this.keysRight = [39];
  44368. this.keysReset = [220];
  44369. this.panningSensibility = 50.0;
  44370. this.zoomingSensibility = 25.0;
  44371. this.useAltToZoom = true;
  44372. }
  44373. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44374. var _this = this;
  44375. if (this._onCanvasBlurObserver) {
  44376. return;
  44377. }
  44378. this._scene = this.camera.getScene();
  44379. this._engine = this._scene.getEngine();
  44380. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44381. _this._keys = [];
  44382. });
  44383. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44384. var evt = info.event;
  44385. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44386. _this._ctrlPressed = evt.ctrlKey;
  44387. _this._altPressed = evt.altKey;
  44388. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44389. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44390. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44391. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44392. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44393. var index = _this._keys.indexOf(evt.keyCode);
  44394. if (index === -1) {
  44395. _this._keys.push(evt.keyCode);
  44396. }
  44397. if (evt.preventDefault) {
  44398. if (!noPreventDefault) {
  44399. evt.preventDefault();
  44400. }
  44401. }
  44402. }
  44403. }
  44404. else {
  44405. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44406. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44407. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44408. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44409. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44410. var index = _this._keys.indexOf(evt.keyCode);
  44411. if (index >= 0) {
  44412. _this._keys.splice(index, 1);
  44413. }
  44414. if (evt.preventDefault) {
  44415. if (!noPreventDefault) {
  44416. evt.preventDefault();
  44417. }
  44418. }
  44419. }
  44420. }
  44421. });
  44422. };
  44423. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44424. if (this._scene) {
  44425. if (this._onKeyboardObserver) {
  44426. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44427. }
  44428. if (this._onCanvasBlurObserver) {
  44429. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44430. }
  44431. this._onKeyboardObserver = null;
  44432. this._onCanvasBlurObserver = null;
  44433. }
  44434. this._keys = [];
  44435. };
  44436. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44437. if (this._onKeyboardObserver) {
  44438. var camera = this.camera;
  44439. for (var index = 0; index < this._keys.length; index++) {
  44440. var keyCode = this._keys[index];
  44441. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44442. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44443. camera.inertialPanningX -= 1 / this.panningSensibility;
  44444. }
  44445. else {
  44446. camera.inertialAlphaOffset -= 0.01;
  44447. }
  44448. }
  44449. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44450. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44451. camera.inertialPanningY += 1 / this.panningSensibility;
  44452. }
  44453. else if (this._altPressed && this.useAltToZoom) {
  44454. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44455. }
  44456. else {
  44457. camera.inertialBetaOffset -= 0.01;
  44458. }
  44459. }
  44460. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44461. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44462. camera.inertialPanningX += 1 / this.panningSensibility;
  44463. }
  44464. else {
  44465. camera.inertialAlphaOffset += 0.01;
  44466. }
  44467. }
  44468. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44469. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44470. camera.inertialPanningY -= 1 / this.panningSensibility;
  44471. }
  44472. else if (this._altPressed && this.useAltToZoom) {
  44473. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44474. }
  44475. else {
  44476. camera.inertialBetaOffset += 0.01;
  44477. }
  44478. }
  44479. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44480. camera.restoreState();
  44481. }
  44482. }
  44483. }
  44484. };
  44485. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44486. return "ArcRotateCameraKeyboardMoveInput";
  44487. };
  44488. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44489. return "keyboard";
  44490. };
  44491. __decorate([
  44492. BABYLON.serialize()
  44493. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44494. __decorate([
  44495. BABYLON.serialize()
  44496. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44497. __decorate([
  44498. BABYLON.serialize()
  44499. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44500. __decorate([
  44501. BABYLON.serialize()
  44502. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44503. __decorate([
  44504. BABYLON.serialize()
  44505. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44506. __decorate([
  44507. BABYLON.serialize()
  44508. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44509. __decorate([
  44510. BABYLON.serialize()
  44511. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44512. __decorate([
  44513. BABYLON.serialize()
  44514. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44515. return ArcRotateCameraKeyboardMoveInput;
  44516. }());
  44517. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44518. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44519. })(BABYLON || (BABYLON = {}));
  44520. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44521. "use strict";
  44522. var BABYLON;
  44523. (function (BABYLON) {
  44524. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44525. function ArcRotateCameraMouseWheelInput() {
  44526. this.wheelPrecision = 3.0;
  44527. /**
  44528. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44529. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44530. */
  44531. this.wheelDeltaPercentage = 0;
  44532. }
  44533. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44534. var _this = this;
  44535. this._wheel = function (p, s) {
  44536. //sanity check - this should be a PointerWheel event.
  44537. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44538. return;
  44539. var event = p.event;
  44540. var delta = 0;
  44541. if (event.wheelDelta) {
  44542. if (_this.wheelDeltaPercentage) {
  44543. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  44544. if (event.wheelDelta > 0) {
  44545. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  44546. }
  44547. else {
  44548. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  44549. }
  44550. }
  44551. else {
  44552. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  44553. }
  44554. }
  44555. else if (event.detail) {
  44556. delta = -event.detail / _this.wheelPrecision;
  44557. }
  44558. if (delta)
  44559. _this.camera.inertialRadiusOffset += delta;
  44560. if (event.preventDefault) {
  44561. if (!noPreventDefault) {
  44562. event.preventDefault();
  44563. }
  44564. }
  44565. };
  44566. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44567. };
  44568. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44569. if (this._observer && element) {
  44570. this.camera.getScene().onPointerObservable.remove(this._observer);
  44571. this._observer = null;
  44572. this._wheel = null;
  44573. }
  44574. };
  44575. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44576. return "ArcRotateCameraMouseWheelInput";
  44577. };
  44578. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44579. return "mousewheel";
  44580. };
  44581. __decorate([
  44582. BABYLON.serialize()
  44583. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44584. __decorate([
  44585. BABYLON.serialize()
  44586. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44587. return ArcRotateCameraMouseWheelInput;
  44588. }());
  44589. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44590. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44591. })(BABYLON || (BABYLON = {}));
  44592. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44593. "use strict";
  44594. var BABYLON;
  44595. (function (BABYLON) {
  44596. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44597. function ArcRotateCameraPointersInput() {
  44598. this.buttons = [0, 1, 2];
  44599. this.angularSensibilityX = 1000.0;
  44600. this.angularSensibilityY = 1000.0;
  44601. this.pinchPrecision = 12.0;
  44602. /**
  44603. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44604. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44605. */
  44606. this.pinchDeltaPercentage = 0;
  44607. this.panningSensibility = 1000.0;
  44608. this.multiTouchPanning = true;
  44609. this.multiTouchPanAndZoom = true;
  44610. this._isPanClick = false;
  44611. this.pinchInwards = true;
  44612. }
  44613. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44614. var _this = this;
  44615. var engine = this.camera.getEngine();
  44616. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44617. var pointA = null;
  44618. var pointB = null;
  44619. var previousPinchSquaredDistance = 0;
  44620. var initialDistance = 0;
  44621. var twoFingerActivityCount = 0;
  44622. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44623. this._pointerInput = function (p, s) {
  44624. var evt = p.event;
  44625. var isTouch = p.event.pointerType === "touch";
  44626. if (engine.isInVRExclusivePointerMode) {
  44627. return;
  44628. }
  44629. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44630. return;
  44631. }
  44632. var srcElement = (evt.srcElement || evt.target);
  44633. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44634. try {
  44635. srcElement.setPointerCapture(evt.pointerId);
  44636. }
  44637. catch (e) {
  44638. //Nothing to do with the error. Execution will continue.
  44639. }
  44640. // Manage panning with pan button click
  44641. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44642. // manage pointers
  44643. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44644. if (pointA === null) {
  44645. pointA = cacheSoloPointer;
  44646. }
  44647. else if (pointB === null) {
  44648. pointB = cacheSoloPointer;
  44649. }
  44650. if (!noPreventDefault) {
  44651. evt.preventDefault();
  44652. element.focus();
  44653. }
  44654. }
  44655. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44656. _this.camera.restoreState();
  44657. }
  44658. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44659. try {
  44660. srcElement.releasePointerCapture(evt.pointerId);
  44661. }
  44662. catch (e) {
  44663. //Nothing to do with the error.
  44664. }
  44665. cacheSoloPointer = null;
  44666. previousPinchSquaredDistance = 0;
  44667. previousMultiTouchPanPosition.isPaning = false;
  44668. previousMultiTouchPanPosition.isPinching = false;
  44669. twoFingerActivityCount = 0;
  44670. initialDistance = 0;
  44671. if (!isTouch) {
  44672. pointB = null; // Mouse and pen are mono pointer
  44673. }
  44674. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44675. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44676. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44677. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44678. if (engine.badOS) {
  44679. pointA = pointB = null;
  44680. }
  44681. else {
  44682. //only remove the impacted pointer in case of multitouch allowing on most
  44683. //platforms switching from rotate to zoom and pan seamlessly.
  44684. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44685. pointA = pointB;
  44686. pointB = null;
  44687. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44688. }
  44689. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44690. pointB = null;
  44691. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44692. }
  44693. else {
  44694. pointA = pointB = null;
  44695. }
  44696. }
  44697. if (!noPreventDefault) {
  44698. evt.preventDefault();
  44699. }
  44700. }
  44701. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44702. if (!noPreventDefault) {
  44703. evt.preventDefault();
  44704. }
  44705. // One button down
  44706. if (pointA && pointB === null && cacheSoloPointer) {
  44707. if (_this.panningSensibility !== 0 &&
  44708. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44709. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44710. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44711. }
  44712. else {
  44713. var offsetX = evt.clientX - cacheSoloPointer.x;
  44714. var offsetY = evt.clientY - cacheSoloPointer.y;
  44715. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44716. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44717. }
  44718. cacheSoloPointer.x = evt.clientX;
  44719. cacheSoloPointer.y = evt.clientY;
  44720. }
  44721. else if (pointA && pointB) {
  44722. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44723. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44724. ed.x = evt.clientX;
  44725. ed.y = evt.clientY;
  44726. var direction = _this.pinchInwards ? 1 : -1;
  44727. var distX = pointA.x - pointB.x;
  44728. var distY = pointA.y - pointB.y;
  44729. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44730. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44731. if (previousPinchSquaredDistance === 0) {
  44732. initialDistance = pinchDistance;
  44733. previousPinchSquaredDistance = pinchSquaredDistance;
  44734. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44735. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44736. return;
  44737. }
  44738. if (_this.multiTouchPanAndZoom) {
  44739. if (_this.pinchDeltaPercentage) {
  44740. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44741. }
  44742. else {
  44743. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44744. (_this.pinchPrecision *
  44745. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44746. direction);
  44747. }
  44748. if (_this.panningSensibility !== 0) {
  44749. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44750. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44751. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44752. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44753. previousMultiTouchPanPosition.x = pointersCenterX;
  44754. previousMultiTouchPanPosition.y = pointersCenterY;
  44755. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44756. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44757. }
  44758. }
  44759. else {
  44760. twoFingerActivityCount++;
  44761. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44762. if (_this.pinchDeltaPercentage) {
  44763. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44764. }
  44765. else {
  44766. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44767. (_this.pinchPrecision *
  44768. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44769. direction);
  44770. }
  44771. previousMultiTouchPanPosition.isPaning = false;
  44772. previousMultiTouchPanPosition.isPinching = true;
  44773. }
  44774. else {
  44775. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44776. if (!previousMultiTouchPanPosition.isPaning) {
  44777. previousMultiTouchPanPosition.isPaning = true;
  44778. previousMultiTouchPanPosition.isPinching = false;
  44779. previousMultiTouchPanPosition.x = ed.x;
  44780. previousMultiTouchPanPosition.y = ed.y;
  44781. return;
  44782. }
  44783. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44784. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44785. }
  44786. }
  44787. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44788. previousMultiTouchPanPosition.x = ed.x;
  44789. previousMultiTouchPanPosition.y = ed.y;
  44790. }
  44791. }
  44792. previousPinchSquaredDistance = pinchSquaredDistance;
  44793. }
  44794. }
  44795. };
  44796. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44797. this._onContextMenu = function (evt) {
  44798. evt.preventDefault();
  44799. };
  44800. if (!this.camera._useCtrlForPanning) {
  44801. element.addEventListener("contextmenu", this._onContextMenu, false);
  44802. }
  44803. this._onLostFocus = function () {
  44804. //this._keys = [];
  44805. pointA = pointB = null;
  44806. previousPinchSquaredDistance = 0;
  44807. previousMultiTouchPanPosition.isPaning = false;
  44808. previousMultiTouchPanPosition.isPinching = false;
  44809. twoFingerActivityCount = 0;
  44810. cacheSoloPointer = null;
  44811. initialDistance = 0;
  44812. };
  44813. this._onMouseMove = function (evt) {
  44814. if (!engine.isPointerLock) {
  44815. return;
  44816. }
  44817. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44818. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44819. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44820. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44821. if (!noPreventDefault) {
  44822. evt.preventDefault();
  44823. }
  44824. };
  44825. this._onGestureStart = function (e) {
  44826. if (window.MSGesture === undefined) {
  44827. return;
  44828. }
  44829. if (!_this._MSGestureHandler) {
  44830. _this._MSGestureHandler = new MSGesture();
  44831. _this._MSGestureHandler.target = element;
  44832. }
  44833. _this._MSGestureHandler.addPointer(e.pointerId);
  44834. };
  44835. this._onGesture = function (e) {
  44836. _this.camera.radius *= e.scale;
  44837. if (e.preventDefault) {
  44838. if (!noPreventDefault) {
  44839. e.stopPropagation();
  44840. e.preventDefault();
  44841. }
  44842. }
  44843. };
  44844. element.addEventListener("mousemove", this._onMouseMove, false);
  44845. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44846. element.addEventListener("MSGestureChange", this._onGesture, false);
  44847. BABYLON.Tools.RegisterTopRootEvents([
  44848. { name: "blur", handler: this._onLostFocus }
  44849. ]);
  44850. };
  44851. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44852. if (this._onLostFocus) {
  44853. BABYLON.Tools.UnregisterTopRootEvents([
  44854. { name: "blur", handler: this._onLostFocus }
  44855. ]);
  44856. }
  44857. if (element && this._observer) {
  44858. this.camera.getScene().onPointerObservable.remove(this._observer);
  44859. this._observer = null;
  44860. if (this._onContextMenu) {
  44861. element.removeEventListener("contextmenu", this._onContextMenu);
  44862. }
  44863. if (this._onMouseMove) {
  44864. element.removeEventListener("mousemove", this._onMouseMove);
  44865. }
  44866. if (this._onGestureStart) {
  44867. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44868. }
  44869. if (this._onGesture) {
  44870. element.removeEventListener("MSGestureChange", this._onGesture);
  44871. }
  44872. this._isPanClick = false;
  44873. this.pinchInwards = true;
  44874. this._onMouseMove = null;
  44875. this._onGestureStart = null;
  44876. this._onGesture = null;
  44877. this._MSGestureHandler = null;
  44878. this._onLostFocus = null;
  44879. this._onContextMenu = null;
  44880. }
  44881. };
  44882. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44883. return "ArcRotateCameraPointersInput";
  44884. };
  44885. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44886. return "pointers";
  44887. };
  44888. __decorate([
  44889. BABYLON.serialize()
  44890. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44891. __decorate([
  44892. BABYLON.serialize()
  44893. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44894. __decorate([
  44895. BABYLON.serialize()
  44896. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44897. __decorate([
  44898. BABYLON.serialize()
  44899. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44900. __decorate([
  44901. BABYLON.serialize()
  44902. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44903. __decorate([
  44904. BABYLON.serialize()
  44905. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44906. __decorate([
  44907. BABYLON.serialize()
  44908. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44909. __decorate([
  44910. BABYLON.serialize()
  44911. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44912. return ArcRotateCameraPointersInput;
  44913. }());
  44914. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44915. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44916. })(BABYLON || (BABYLON = {}));
  44917. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44918. "use strict";
  44919. var BABYLON;
  44920. (function (BABYLON) {
  44921. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44922. __extends(ArcRotateCameraInputsManager, _super);
  44923. function ArcRotateCameraInputsManager(camera) {
  44924. return _super.call(this, camera) || this;
  44925. }
  44926. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44927. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44928. return this;
  44929. };
  44930. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44931. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44932. return this;
  44933. };
  44934. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44935. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44936. return this;
  44937. };
  44938. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44939. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44940. return this;
  44941. };
  44942. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44943. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44944. return this;
  44945. };
  44946. return ArcRotateCameraInputsManager;
  44947. }(BABYLON.CameraInputsManager));
  44948. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44949. })(BABYLON || (BABYLON = {}));
  44950. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44951. "use strict";
  44952. var BABYLON;
  44953. (function (BABYLON) {
  44954. var ArcRotateCamera = /** @class */ (function (_super) {
  44955. __extends(ArcRotateCamera, _super);
  44956. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44957. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44958. _this.inertialAlphaOffset = 0;
  44959. _this.inertialBetaOffset = 0;
  44960. _this.inertialRadiusOffset = 0;
  44961. _this.lowerAlphaLimit = null;
  44962. _this.upperAlphaLimit = null;
  44963. _this.lowerBetaLimit = 0.01;
  44964. _this.upperBetaLimit = Math.PI;
  44965. _this.lowerRadiusLimit = null;
  44966. _this.upperRadiusLimit = null;
  44967. _this.inertialPanningX = 0;
  44968. _this.inertialPanningY = 0;
  44969. _this.pinchToPanMaxDistance = 20;
  44970. _this.panningDistanceLimit = null;
  44971. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44972. _this.panningInertia = 0.9;
  44973. //-- end properties for backward compatibility for inputs
  44974. _this.zoomOnFactor = 1;
  44975. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44976. _this.allowUpsideDown = true;
  44977. _this._viewMatrix = new BABYLON.Matrix();
  44978. // Panning
  44979. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44980. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44981. _this.checkCollisions = false;
  44982. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44983. _this._previousPosition = BABYLON.Vector3.Zero();
  44984. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44985. _this._newPosition = BABYLON.Vector3.Zero();
  44986. _this._computationVector = BABYLON.Vector3.Zero();
  44987. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44988. if (collidedMesh === void 0) { collidedMesh = null; }
  44989. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44990. newPosition.multiplyInPlace(_this._collider._radius);
  44991. }
  44992. if (!collidedMesh) {
  44993. _this._previousPosition.copyFrom(_this.position);
  44994. }
  44995. else {
  44996. _this.setPosition(newPosition);
  44997. if (_this.onCollide) {
  44998. _this.onCollide(collidedMesh);
  44999. }
  45000. }
  45001. // Recompute because of constraints
  45002. var cosa = Math.cos(_this.alpha);
  45003. var sina = Math.sin(_this.alpha);
  45004. var cosb = Math.cos(_this.beta);
  45005. var sinb = Math.sin(_this.beta);
  45006. if (sinb === 0) {
  45007. sinb = 0.0001;
  45008. }
  45009. var target = _this._getTargetPosition();
  45010. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45011. target.addToRef(_this._computationVector, _this._newPosition);
  45012. _this.position.copyFrom(_this._newPosition);
  45013. var up = _this.upVector;
  45014. if (_this.allowUpsideDown && _this.beta < 0) {
  45015. up = up.clone();
  45016. up = up.negate();
  45017. }
  45018. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45019. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45020. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45021. _this._collisionTriggered = false;
  45022. };
  45023. _this._target = BABYLON.Vector3.Zero();
  45024. if (target) {
  45025. _this.setTarget(target);
  45026. }
  45027. _this.alpha = alpha;
  45028. _this.beta = beta;
  45029. _this.radius = radius;
  45030. _this.getViewMatrix();
  45031. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45032. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45033. return _this;
  45034. }
  45035. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45036. get: function () {
  45037. return this._target;
  45038. },
  45039. set: function (value) {
  45040. this.setTarget(value);
  45041. },
  45042. enumerable: true,
  45043. configurable: true
  45044. });
  45045. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45046. //-- begin properties for backward compatibility for inputs
  45047. get: function () {
  45048. var pointers = this.inputs.attached["pointers"];
  45049. if (pointers)
  45050. return pointers.angularSensibilityX;
  45051. return 0;
  45052. },
  45053. set: function (value) {
  45054. var pointers = this.inputs.attached["pointers"];
  45055. if (pointers) {
  45056. pointers.angularSensibilityX = value;
  45057. }
  45058. },
  45059. enumerable: true,
  45060. configurable: true
  45061. });
  45062. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45063. get: function () {
  45064. var pointers = this.inputs.attached["pointers"];
  45065. if (pointers)
  45066. return pointers.angularSensibilityY;
  45067. return 0;
  45068. },
  45069. set: function (value) {
  45070. var pointers = this.inputs.attached["pointers"];
  45071. if (pointers) {
  45072. pointers.angularSensibilityY = value;
  45073. }
  45074. },
  45075. enumerable: true,
  45076. configurable: true
  45077. });
  45078. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45079. get: function () {
  45080. var pointers = this.inputs.attached["pointers"];
  45081. if (pointers)
  45082. return pointers.pinchPrecision;
  45083. return 0;
  45084. },
  45085. set: function (value) {
  45086. var pointers = this.inputs.attached["pointers"];
  45087. if (pointers) {
  45088. pointers.pinchPrecision = value;
  45089. }
  45090. },
  45091. enumerable: true,
  45092. configurable: true
  45093. });
  45094. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45095. get: function () {
  45096. var pointers = this.inputs.attached["pointers"];
  45097. if (pointers)
  45098. return pointers.pinchDeltaPercentage;
  45099. return 0;
  45100. },
  45101. set: function (value) {
  45102. var pointers = this.inputs.attached["pointers"];
  45103. if (pointers) {
  45104. pointers.pinchDeltaPercentage = value;
  45105. }
  45106. },
  45107. enumerable: true,
  45108. configurable: true
  45109. });
  45110. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45111. get: function () {
  45112. var pointers = this.inputs.attached["pointers"];
  45113. if (pointers)
  45114. return pointers.panningSensibility;
  45115. return 0;
  45116. },
  45117. set: function (value) {
  45118. var pointers = this.inputs.attached["pointers"];
  45119. if (pointers) {
  45120. pointers.panningSensibility = value;
  45121. }
  45122. },
  45123. enumerable: true,
  45124. configurable: true
  45125. });
  45126. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45127. get: function () {
  45128. var keyboard = this.inputs.attached["keyboard"];
  45129. if (keyboard)
  45130. return keyboard.keysUp;
  45131. return [];
  45132. },
  45133. set: function (value) {
  45134. var keyboard = this.inputs.attached["keyboard"];
  45135. if (keyboard)
  45136. keyboard.keysUp = value;
  45137. },
  45138. enumerable: true,
  45139. configurable: true
  45140. });
  45141. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45142. get: function () {
  45143. var keyboard = this.inputs.attached["keyboard"];
  45144. if (keyboard)
  45145. return keyboard.keysDown;
  45146. return [];
  45147. },
  45148. set: function (value) {
  45149. var keyboard = this.inputs.attached["keyboard"];
  45150. if (keyboard)
  45151. keyboard.keysDown = value;
  45152. },
  45153. enumerable: true,
  45154. configurable: true
  45155. });
  45156. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45157. get: function () {
  45158. var keyboard = this.inputs.attached["keyboard"];
  45159. if (keyboard)
  45160. return keyboard.keysLeft;
  45161. return [];
  45162. },
  45163. set: function (value) {
  45164. var keyboard = this.inputs.attached["keyboard"];
  45165. if (keyboard)
  45166. keyboard.keysLeft = value;
  45167. },
  45168. enumerable: true,
  45169. configurable: true
  45170. });
  45171. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45172. get: function () {
  45173. var keyboard = this.inputs.attached["keyboard"];
  45174. if (keyboard)
  45175. return keyboard.keysRight;
  45176. return [];
  45177. },
  45178. set: function (value) {
  45179. var keyboard = this.inputs.attached["keyboard"];
  45180. if (keyboard)
  45181. keyboard.keysRight = value;
  45182. },
  45183. enumerable: true,
  45184. configurable: true
  45185. });
  45186. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45187. get: function () {
  45188. var mousewheel = this.inputs.attached["mousewheel"];
  45189. if (mousewheel)
  45190. return mousewheel.wheelPrecision;
  45191. return 0;
  45192. },
  45193. set: function (value) {
  45194. var mousewheel = this.inputs.attached["mousewheel"];
  45195. if (mousewheel)
  45196. mousewheel.wheelPrecision = value;
  45197. },
  45198. enumerable: true,
  45199. configurable: true
  45200. });
  45201. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45202. get: function () {
  45203. var mousewheel = this.inputs.attached["mousewheel"];
  45204. if (mousewheel)
  45205. return mousewheel.wheelDeltaPercentage;
  45206. return 0;
  45207. },
  45208. set: function (value) {
  45209. var mousewheel = this.inputs.attached["mousewheel"];
  45210. if (mousewheel)
  45211. mousewheel.wheelDeltaPercentage = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45217. get: function () {
  45218. return this._bouncingBehavior;
  45219. },
  45220. enumerable: true,
  45221. configurable: true
  45222. });
  45223. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45224. get: function () {
  45225. return this._bouncingBehavior != null;
  45226. },
  45227. set: function (value) {
  45228. if (value === this.useBouncingBehavior) {
  45229. return;
  45230. }
  45231. if (value) {
  45232. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45233. this.addBehavior(this._bouncingBehavior);
  45234. }
  45235. else if (this._bouncingBehavior) {
  45236. this.removeBehavior(this._bouncingBehavior);
  45237. this._bouncingBehavior = null;
  45238. }
  45239. },
  45240. enumerable: true,
  45241. configurable: true
  45242. });
  45243. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45244. get: function () {
  45245. return this._framingBehavior;
  45246. },
  45247. enumerable: true,
  45248. configurable: true
  45249. });
  45250. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45251. get: function () {
  45252. return this._framingBehavior != null;
  45253. },
  45254. set: function (value) {
  45255. if (value === this.useFramingBehavior) {
  45256. return;
  45257. }
  45258. if (value) {
  45259. this._framingBehavior = new BABYLON.FramingBehavior();
  45260. this.addBehavior(this._framingBehavior);
  45261. }
  45262. else if (this._framingBehavior) {
  45263. this.removeBehavior(this._framingBehavior);
  45264. this._framingBehavior = null;
  45265. }
  45266. },
  45267. enumerable: true,
  45268. configurable: true
  45269. });
  45270. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45271. get: function () {
  45272. return this._autoRotationBehavior;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45278. get: function () {
  45279. return this._autoRotationBehavior != null;
  45280. },
  45281. set: function (value) {
  45282. if (value === this.useAutoRotationBehavior) {
  45283. return;
  45284. }
  45285. if (value) {
  45286. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45287. this.addBehavior(this._autoRotationBehavior);
  45288. }
  45289. else if (this._autoRotationBehavior) {
  45290. this.removeBehavior(this._autoRotationBehavior);
  45291. this._autoRotationBehavior = null;
  45292. }
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. // Cache
  45298. ArcRotateCamera.prototype._initCache = function () {
  45299. _super.prototype._initCache.call(this);
  45300. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45301. this._cache.alpha = undefined;
  45302. this._cache.beta = undefined;
  45303. this._cache.radius = undefined;
  45304. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45305. };
  45306. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45307. if (!ignoreParentClass) {
  45308. _super.prototype._updateCache.call(this);
  45309. }
  45310. this._cache._target.copyFrom(this._getTargetPosition());
  45311. this._cache.alpha = this.alpha;
  45312. this._cache.beta = this.beta;
  45313. this._cache.radius = this.radius;
  45314. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45315. };
  45316. ArcRotateCamera.prototype._getTargetPosition = function () {
  45317. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45318. var pos = this._targetHost.getAbsolutePosition();
  45319. if (this._targetBoundingCenter) {
  45320. pos.addToRef(this._targetBoundingCenter, this._target);
  45321. }
  45322. else {
  45323. this._target.copyFrom(pos);
  45324. }
  45325. }
  45326. var lockedTargetPosition = this._getLockedTargetPosition();
  45327. if (lockedTargetPosition) {
  45328. return lockedTargetPosition;
  45329. }
  45330. return this._target;
  45331. };
  45332. ArcRotateCamera.prototype.storeState = function () {
  45333. this._storedAlpha = this.alpha;
  45334. this._storedBeta = this.beta;
  45335. this._storedRadius = this.radius;
  45336. this._storedTarget = this._getTargetPosition().clone();
  45337. return _super.prototype.storeState.call(this);
  45338. };
  45339. /**
  45340. * Restored camera state. You must call storeState() first
  45341. */
  45342. ArcRotateCamera.prototype._restoreStateValues = function () {
  45343. if (!_super.prototype._restoreStateValues.call(this)) {
  45344. return false;
  45345. }
  45346. this.alpha = this._storedAlpha;
  45347. this.beta = this._storedBeta;
  45348. this.radius = this._storedRadius;
  45349. this.setTarget(this._storedTarget.clone());
  45350. this.inertialAlphaOffset = 0;
  45351. this.inertialBetaOffset = 0;
  45352. this.inertialRadiusOffset = 0;
  45353. this.inertialPanningX = 0;
  45354. this.inertialPanningY = 0;
  45355. return true;
  45356. };
  45357. // Synchronized
  45358. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45359. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45360. return false;
  45361. return this._cache._target.equals(this._getTargetPosition())
  45362. && this._cache.alpha === this.alpha
  45363. && this._cache.beta === this.beta
  45364. && this._cache.radius === this.radius
  45365. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45366. };
  45367. // Methods
  45368. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45369. var _this = this;
  45370. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45371. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45372. this._useCtrlForPanning = useCtrlForPanning;
  45373. this._panningMouseButton = panningMouseButton;
  45374. this.inputs.attachElement(element, noPreventDefault);
  45375. this._reset = function () {
  45376. _this.inertialAlphaOffset = 0;
  45377. _this.inertialBetaOffset = 0;
  45378. _this.inertialRadiusOffset = 0;
  45379. _this.inertialPanningX = 0;
  45380. _this.inertialPanningY = 0;
  45381. };
  45382. };
  45383. ArcRotateCamera.prototype.detachControl = function (element) {
  45384. this.inputs.detachElement(element);
  45385. if (this._reset) {
  45386. this._reset();
  45387. }
  45388. };
  45389. ArcRotateCamera.prototype._checkInputs = function () {
  45390. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45391. if (this._collisionTriggered) {
  45392. return;
  45393. }
  45394. this.inputs.checkInputs();
  45395. // Inertia
  45396. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45397. if (this.getScene().useRightHandedSystem) {
  45398. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45399. }
  45400. else {
  45401. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45402. }
  45403. this.beta += this.inertialBetaOffset;
  45404. this.radius -= this.inertialRadiusOffset;
  45405. this.inertialAlphaOffset *= this.inertia;
  45406. this.inertialBetaOffset *= this.inertia;
  45407. this.inertialRadiusOffset *= this.inertia;
  45408. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45409. this.inertialAlphaOffset = 0;
  45410. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45411. this.inertialBetaOffset = 0;
  45412. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45413. this.inertialRadiusOffset = 0;
  45414. }
  45415. // Panning inertia
  45416. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45417. if (!this._localDirection) {
  45418. this._localDirection = BABYLON.Vector3.Zero();
  45419. this._transformedDirection = BABYLON.Vector3.Zero();
  45420. }
  45421. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45422. this._localDirection.multiplyInPlace(this.panningAxis);
  45423. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45424. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45425. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45426. if (!this.panningAxis.y) {
  45427. this._transformedDirection.y = 0;
  45428. }
  45429. if (!this._targetHost) {
  45430. if (this.panningDistanceLimit) {
  45431. this._transformedDirection.addInPlace(this._target);
  45432. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45433. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45434. this._target.copyFrom(this._transformedDirection);
  45435. }
  45436. }
  45437. else {
  45438. this._target.addInPlace(this._transformedDirection);
  45439. }
  45440. }
  45441. this.inertialPanningX *= this.panningInertia;
  45442. this.inertialPanningY *= this.panningInertia;
  45443. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45444. this.inertialPanningX = 0;
  45445. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45446. this.inertialPanningY = 0;
  45447. }
  45448. // Limits
  45449. this._checkLimits();
  45450. _super.prototype._checkInputs.call(this);
  45451. };
  45452. ArcRotateCamera.prototype._checkLimits = function () {
  45453. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45454. if (this.allowUpsideDown && this.beta > Math.PI) {
  45455. this.beta = this.beta - (2 * Math.PI);
  45456. }
  45457. }
  45458. else {
  45459. if (this.beta < this.lowerBetaLimit) {
  45460. this.beta = this.lowerBetaLimit;
  45461. }
  45462. }
  45463. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45464. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45465. this.beta = this.beta + (2 * Math.PI);
  45466. }
  45467. }
  45468. else {
  45469. if (this.beta > this.upperBetaLimit) {
  45470. this.beta = this.upperBetaLimit;
  45471. }
  45472. }
  45473. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45474. this.alpha = this.lowerAlphaLimit;
  45475. }
  45476. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45477. this.alpha = this.upperAlphaLimit;
  45478. }
  45479. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45480. this.radius = this.lowerRadiusLimit;
  45481. }
  45482. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45483. this.radius = this.upperRadiusLimit;
  45484. }
  45485. };
  45486. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45487. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45488. this.radius = this._computationVector.length();
  45489. if (this.radius === 0) {
  45490. this.radius = 0.0001; // Just to avoid division by zero
  45491. }
  45492. // Alpha
  45493. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45494. if (this._computationVector.z < 0) {
  45495. this.alpha = 2 * Math.PI - this.alpha;
  45496. }
  45497. // Beta
  45498. this.beta = Math.acos(this._computationVector.y / this.radius);
  45499. this._checkLimits();
  45500. };
  45501. ArcRotateCamera.prototype.setPosition = function (position) {
  45502. if (this.position.equals(position)) {
  45503. return;
  45504. }
  45505. this.position.copyFrom(position);
  45506. this.rebuildAnglesAndRadius();
  45507. };
  45508. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45509. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45510. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45511. if (target.getBoundingInfo) {
  45512. if (toBoundingCenter) {
  45513. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45514. }
  45515. else {
  45516. this._targetBoundingCenter = null;
  45517. }
  45518. this._targetHost = target;
  45519. this._target = this._getTargetPosition();
  45520. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45521. }
  45522. else {
  45523. var newTarget = target;
  45524. var currentTarget = this._getTargetPosition();
  45525. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45526. return;
  45527. }
  45528. this._targetHost = null;
  45529. this._target = newTarget;
  45530. this._targetBoundingCenter = null;
  45531. this.onMeshTargetChangedObservable.notifyObservers(null);
  45532. }
  45533. this.rebuildAnglesAndRadius();
  45534. };
  45535. ArcRotateCamera.prototype._getViewMatrix = function () {
  45536. // Compute
  45537. var cosa = Math.cos(this.alpha);
  45538. var sina = Math.sin(this.alpha);
  45539. var cosb = Math.cos(this.beta);
  45540. var sinb = Math.sin(this.beta);
  45541. if (sinb === 0) {
  45542. sinb = 0.0001;
  45543. }
  45544. var target = this._getTargetPosition();
  45545. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45546. target.addToRef(this._computationVector, this._newPosition);
  45547. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45548. if (!this._collider) {
  45549. this._collider = new BABYLON.Collider();
  45550. }
  45551. this._collider._radius = this.collisionRadius;
  45552. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45553. this._collisionTriggered = true;
  45554. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45555. }
  45556. else {
  45557. this.position.copyFrom(this._newPosition);
  45558. var up = this.upVector;
  45559. if (this.allowUpsideDown && sinb < 0) {
  45560. up = up.clone();
  45561. up = up.negate();
  45562. }
  45563. if (this.getScene().useRightHandedSystem) {
  45564. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45565. }
  45566. else {
  45567. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45568. }
  45569. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45570. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45571. }
  45572. this._currentTarget = target;
  45573. return this._viewMatrix;
  45574. };
  45575. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45576. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45577. meshes = meshes || this.getScene().meshes;
  45578. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45579. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45580. this.radius = distance * this.zoomOnFactor;
  45581. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45582. };
  45583. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45584. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45585. var meshesOrMinMaxVector;
  45586. var distance;
  45587. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45588. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45589. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45590. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45591. }
  45592. else {
  45593. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45594. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45595. distance = minMaxVectorAndDistance.distance;
  45596. }
  45597. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45598. if (!doNotUpdateMaxZ) {
  45599. this.maxZ = distance * 2;
  45600. }
  45601. };
  45602. /**
  45603. * @override
  45604. * Override Camera.createRigCamera
  45605. */
  45606. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45607. var alphaShift = 0;
  45608. switch (this.cameraRigMode) {
  45609. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45610. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45611. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45612. case BABYLON.Camera.RIG_MODE_VR:
  45613. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45614. break;
  45615. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45616. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45617. break;
  45618. }
  45619. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45620. rigCam._cameraRigParams = {};
  45621. return rigCam;
  45622. };
  45623. /**
  45624. * @override
  45625. * Override Camera._updateRigCameras
  45626. */
  45627. ArcRotateCamera.prototype._updateRigCameras = function () {
  45628. var camLeft = this._rigCameras[0];
  45629. var camRight = this._rigCameras[1];
  45630. camLeft.beta = camRight.beta = this.beta;
  45631. camLeft.radius = camRight.radius = this.radius;
  45632. switch (this.cameraRigMode) {
  45633. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45634. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45636. case BABYLON.Camera.RIG_MODE_VR:
  45637. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45638. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45639. break;
  45640. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45641. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45642. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45643. break;
  45644. }
  45645. _super.prototype._updateRigCameras.call(this);
  45646. };
  45647. ArcRotateCamera.prototype.dispose = function () {
  45648. this.inputs.clear();
  45649. _super.prototype.dispose.call(this);
  45650. };
  45651. ArcRotateCamera.prototype.getClassName = function () {
  45652. return "ArcRotateCamera";
  45653. };
  45654. __decorate([
  45655. BABYLON.serialize()
  45656. ], ArcRotateCamera.prototype, "alpha", void 0);
  45657. __decorate([
  45658. BABYLON.serialize()
  45659. ], ArcRotateCamera.prototype, "beta", void 0);
  45660. __decorate([
  45661. BABYLON.serialize()
  45662. ], ArcRotateCamera.prototype, "radius", void 0);
  45663. __decorate([
  45664. BABYLON.serializeAsVector3("target")
  45665. ], ArcRotateCamera.prototype, "_target", void 0);
  45666. __decorate([
  45667. BABYLON.serialize()
  45668. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45669. __decorate([
  45670. BABYLON.serialize()
  45671. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45672. __decorate([
  45673. BABYLON.serialize()
  45674. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45675. __decorate([
  45676. BABYLON.serialize()
  45677. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45678. __decorate([
  45679. BABYLON.serialize()
  45680. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45681. __decorate([
  45682. BABYLON.serialize()
  45683. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45684. __decorate([
  45685. BABYLON.serialize()
  45686. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45687. __decorate([
  45688. BABYLON.serialize()
  45689. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45690. __decorate([
  45691. BABYLON.serialize()
  45692. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45693. __decorate([
  45694. BABYLON.serialize()
  45695. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45696. __decorate([
  45697. BABYLON.serialize()
  45698. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45699. __decorate([
  45700. BABYLON.serialize()
  45701. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45702. __decorate([
  45703. BABYLON.serialize()
  45704. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45705. __decorate([
  45706. BABYLON.serializeAsVector3()
  45707. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45708. __decorate([
  45709. BABYLON.serialize()
  45710. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45711. __decorate([
  45712. BABYLON.serialize()
  45713. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45714. __decorate([
  45715. BABYLON.serialize()
  45716. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45717. return ArcRotateCamera;
  45718. }(BABYLON.TargetCamera));
  45719. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45720. })(BABYLON || (BABYLON = {}));
  45721. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45722. "use strict";
  45723. var BABYLON;
  45724. (function (BABYLON) {
  45725. /**
  45726. * The HemisphericLight simulates the ambient environment light,
  45727. * so the passed direction is the light reflection direction, not the incoming direction.
  45728. */
  45729. var HemisphericLight = /** @class */ (function (_super) {
  45730. __extends(HemisphericLight, _super);
  45731. /**
  45732. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45733. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45734. * The HemisphericLight can't cast shadows.
  45735. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45736. * @param name The friendly name of the light
  45737. * @param direction The direction of the light reflection
  45738. * @param scene The scene the light belongs to
  45739. */
  45740. function HemisphericLight(name, direction, scene) {
  45741. var _this = _super.call(this, name, scene) || this;
  45742. /**
  45743. * The groundColor is the light in the opposite direction to the one specified during creation.
  45744. * 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.
  45745. */
  45746. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45747. _this.direction = direction || BABYLON.Vector3.Up();
  45748. return _this;
  45749. }
  45750. HemisphericLight.prototype._buildUniformLayout = function () {
  45751. this._uniformBuffer.addUniform("vLightData", 4);
  45752. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45753. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45754. this._uniformBuffer.addUniform("vLightGround", 3);
  45755. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45756. this._uniformBuffer.addUniform("depthValues", 2);
  45757. this._uniformBuffer.create();
  45758. };
  45759. /**
  45760. * Returns the string "HemisphericLight".
  45761. * @return The class name
  45762. */
  45763. HemisphericLight.prototype.getClassName = function () {
  45764. return "HemisphericLight";
  45765. };
  45766. /**
  45767. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45768. * Returns the updated direction.
  45769. * @param target The target the direction should point to
  45770. * @return The computed direction
  45771. */
  45772. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45773. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45774. return this.direction;
  45775. };
  45776. /**
  45777. * Returns the shadow generator associated to the light.
  45778. * @returns Always null for hemispheric lights because it does not support shadows.
  45779. */
  45780. HemisphericLight.prototype.getShadowGenerator = function () {
  45781. return null;
  45782. };
  45783. /**
  45784. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45785. * @param effect The effect to update
  45786. * @param lightIndex The index of the light in the effect to update
  45787. * @returns The hemispheric light
  45788. */
  45789. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45790. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45791. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45792. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45793. return this;
  45794. };
  45795. /**
  45796. * @ignore internal use only.
  45797. */
  45798. HemisphericLight.prototype._getWorldMatrix = function () {
  45799. if (!this._worldMatrix) {
  45800. this._worldMatrix = BABYLON.Matrix.Identity();
  45801. }
  45802. return this._worldMatrix;
  45803. };
  45804. /**
  45805. * Returns the integer 3.
  45806. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45807. */
  45808. HemisphericLight.prototype.getTypeID = function () {
  45809. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45810. };
  45811. __decorate([
  45812. BABYLON.serializeAsColor3()
  45813. ], HemisphericLight.prototype, "groundColor", void 0);
  45814. __decorate([
  45815. BABYLON.serializeAsVector3()
  45816. ], HemisphericLight.prototype, "direction", void 0);
  45817. return HemisphericLight;
  45818. }(BABYLON.Light));
  45819. BABYLON.HemisphericLight = HemisphericLight;
  45820. })(BABYLON || (BABYLON = {}));
  45821. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45822. "use strict";
  45823. var BABYLON;
  45824. (function (BABYLON) {
  45825. /**
  45826. * Base implementation IShadowLight
  45827. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45828. */
  45829. var ShadowLight = /** @class */ (function (_super) {
  45830. __extends(ShadowLight, _super);
  45831. function ShadowLight() {
  45832. var _this = _super !== null && _super.apply(this, arguments) || this;
  45833. _this._needProjectionMatrixCompute = true;
  45834. return _this;
  45835. }
  45836. ShadowLight.prototype._setPosition = function (value) {
  45837. this._position = value;
  45838. };
  45839. Object.defineProperty(ShadowLight.prototype, "position", {
  45840. /**
  45841. * Sets the position the shadow will be casted from. Also use as the light position for both
  45842. * point and spot lights.
  45843. */
  45844. get: function () {
  45845. return this._position;
  45846. },
  45847. /**
  45848. * Sets the position the shadow will be casted from. Also use as the light position for both
  45849. * point and spot lights.
  45850. */
  45851. set: function (value) {
  45852. this._setPosition(value);
  45853. },
  45854. enumerable: true,
  45855. configurable: true
  45856. });
  45857. ShadowLight.prototype._setDirection = function (value) {
  45858. this._direction = value;
  45859. };
  45860. Object.defineProperty(ShadowLight.prototype, "direction", {
  45861. /**
  45862. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45863. * Also use as the light direction on spot and directional lights.
  45864. */
  45865. get: function () {
  45866. return this._direction;
  45867. },
  45868. /**
  45869. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45870. * Also use as the light direction on spot and directional lights.
  45871. */
  45872. set: function (value) {
  45873. this._setDirection(value);
  45874. },
  45875. enumerable: true,
  45876. configurable: true
  45877. });
  45878. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45879. /**
  45880. * Gets the shadow projection clipping minimum z value.
  45881. */
  45882. get: function () {
  45883. return this._shadowMinZ;
  45884. },
  45885. /**
  45886. * Sets the shadow projection clipping minimum z value.
  45887. */
  45888. set: function (value) {
  45889. this._shadowMinZ = value;
  45890. this.forceProjectionMatrixCompute();
  45891. },
  45892. enumerable: true,
  45893. configurable: true
  45894. });
  45895. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45896. /**
  45897. * Sets the shadow projection clipping maximum z value.
  45898. */
  45899. get: function () {
  45900. return this._shadowMaxZ;
  45901. },
  45902. /**
  45903. * Gets the shadow projection clipping maximum z value.
  45904. */
  45905. set: function (value) {
  45906. this._shadowMaxZ = value;
  45907. this.forceProjectionMatrixCompute();
  45908. },
  45909. enumerable: true,
  45910. configurable: true
  45911. });
  45912. /**
  45913. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45914. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45915. */
  45916. ShadowLight.prototype.computeTransformedInformation = function () {
  45917. if (this.parent && this.parent.getWorldMatrix) {
  45918. if (!this.transformedPosition) {
  45919. this.transformedPosition = BABYLON.Vector3.Zero();
  45920. }
  45921. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45922. // In case the direction is present.
  45923. if (this.direction) {
  45924. if (!this.transformedDirection) {
  45925. this.transformedDirection = BABYLON.Vector3.Zero();
  45926. }
  45927. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45928. }
  45929. return true;
  45930. }
  45931. return false;
  45932. };
  45933. /**
  45934. * Return the depth scale used for the shadow map.
  45935. * @returns the depth scale.
  45936. */
  45937. ShadowLight.prototype.getDepthScale = function () {
  45938. return 50.0;
  45939. };
  45940. /**
  45941. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45942. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45943. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45944. */
  45945. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45946. return this.transformedDirection ? this.transformedDirection : this.direction;
  45947. };
  45948. /**
  45949. * Returns the ShadowLight absolute position in the World.
  45950. * @returns the position vector in world space
  45951. */
  45952. ShadowLight.prototype.getAbsolutePosition = function () {
  45953. return this.transformedPosition ? this.transformedPosition : this.position;
  45954. };
  45955. /**
  45956. * Sets the ShadowLight direction toward the passed target.
  45957. * @param target The point tot target in local space
  45958. * @returns the updated ShadowLight direction
  45959. */
  45960. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45961. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45962. return this.direction;
  45963. };
  45964. /**
  45965. * Returns the light rotation in euler definition.
  45966. * @returns the x y z rotation in local space.
  45967. */
  45968. ShadowLight.prototype.getRotation = function () {
  45969. this.direction.normalize();
  45970. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45971. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45972. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  45973. };
  45974. /**
  45975. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45976. * @returns true if a cube texture needs to be use
  45977. */
  45978. ShadowLight.prototype.needCube = function () {
  45979. return false;
  45980. };
  45981. /**
  45982. * Detects if the projection matrix requires to be recomputed this frame.
  45983. * @returns true if it requires to be recomputed otherwise, false.
  45984. */
  45985. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45986. return this._needProjectionMatrixCompute;
  45987. };
  45988. /**
  45989. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45990. */
  45991. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45992. this._needProjectionMatrixCompute = true;
  45993. };
  45994. /**
  45995. * Get the world matrix of the sahdow lights.
  45996. * @ignore Internal Use Only
  45997. */
  45998. ShadowLight.prototype._getWorldMatrix = function () {
  45999. if (!this._worldMatrix) {
  46000. this._worldMatrix = BABYLON.Matrix.Identity();
  46001. }
  46002. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46003. return this._worldMatrix;
  46004. };
  46005. /**
  46006. * Gets the minZ used for shadow according to both the scene and the light.
  46007. * @param activeCamera The camera we are returning the min for
  46008. * @returns the depth min z
  46009. */
  46010. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46011. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46012. };
  46013. /**
  46014. * Gets the maxZ used for shadow according to both the scene and the light.
  46015. * @param activeCamera The camera we are returning the max for
  46016. * @returns the depth max z
  46017. */
  46018. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46019. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46020. };
  46021. /**
  46022. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46023. * @param matrix The materix to updated with the projection information
  46024. * @param viewMatrix The transform matrix of the light
  46025. * @param renderList The list of mesh to render in the map
  46026. * @returns The current light
  46027. */
  46028. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46029. if (this.customProjectionMatrixBuilder) {
  46030. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46031. }
  46032. else {
  46033. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46034. }
  46035. return this;
  46036. };
  46037. __decorate([
  46038. BABYLON.serializeAsVector3()
  46039. ], ShadowLight.prototype, "position", null);
  46040. __decorate([
  46041. BABYLON.serializeAsVector3()
  46042. ], ShadowLight.prototype, "direction", null);
  46043. __decorate([
  46044. BABYLON.serialize()
  46045. ], ShadowLight.prototype, "shadowMinZ", null);
  46046. __decorate([
  46047. BABYLON.serialize()
  46048. ], ShadowLight.prototype, "shadowMaxZ", null);
  46049. return ShadowLight;
  46050. }(BABYLON.Light));
  46051. BABYLON.ShadowLight = ShadowLight;
  46052. })(BABYLON || (BABYLON = {}));
  46053. //# sourceMappingURL=babylon.shadowLight.js.map
  46054. "use strict";
  46055. var BABYLON;
  46056. (function (BABYLON) {
  46057. /**
  46058. * A point light is a light defined by an unique point in world space.
  46059. * The light is emitted in every direction from this point.
  46060. * A good example of a point light is a standard light bulb.
  46061. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46062. */
  46063. var PointLight = /** @class */ (function (_super) {
  46064. __extends(PointLight, _super);
  46065. /**
  46066. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46067. * A PointLight emits the light in every direction.
  46068. * It can cast shadows.
  46069. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46070. * ```javascript
  46071. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46072. * ```
  46073. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46074. * @param name The light friendly name
  46075. * @param position The position of the point light in the scene
  46076. * @param scene The scene the lights belongs to
  46077. */
  46078. function PointLight(name, position, scene) {
  46079. var _this = _super.call(this, name, scene) || this;
  46080. _this._shadowAngle = Math.PI / 2;
  46081. _this.position = position;
  46082. return _this;
  46083. }
  46084. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46085. /**
  46086. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46087. * This specifies what angle the shadow will use to be created.
  46088. *
  46089. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46090. */
  46091. get: function () {
  46092. return this._shadowAngle;
  46093. },
  46094. /**
  46095. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46096. * This specifies what angle the shadow will use to be created.
  46097. *
  46098. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46099. */
  46100. set: function (value) {
  46101. this._shadowAngle = value;
  46102. this.forceProjectionMatrixCompute();
  46103. },
  46104. enumerable: true,
  46105. configurable: true
  46106. });
  46107. Object.defineProperty(PointLight.prototype, "direction", {
  46108. /**
  46109. * Gets the direction if it has been set.
  46110. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46111. */
  46112. get: function () {
  46113. return this._direction;
  46114. },
  46115. /**
  46116. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46117. */
  46118. set: function (value) {
  46119. var previousNeedCube = this.needCube();
  46120. this._direction = value;
  46121. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46122. this._shadowGenerator.recreateShadowMap();
  46123. }
  46124. },
  46125. enumerable: true,
  46126. configurable: true
  46127. });
  46128. /**
  46129. * Returns the string "PointLight"
  46130. * @returns the class name
  46131. */
  46132. PointLight.prototype.getClassName = function () {
  46133. return "PointLight";
  46134. };
  46135. /**
  46136. * Returns the integer 0.
  46137. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46138. */
  46139. PointLight.prototype.getTypeID = function () {
  46140. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46141. };
  46142. /**
  46143. * Specifies wether or not the shadowmap should be a cube texture.
  46144. * @returns true if the shadowmap needs to be a cube texture.
  46145. */
  46146. PointLight.prototype.needCube = function () {
  46147. return !this.direction;
  46148. };
  46149. /**
  46150. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46151. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46152. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46153. */
  46154. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46155. if (this.direction) {
  46156. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46157. }
  46158. else {
  46159. switch (faceIndex) {
  46160. case 0:
  46161. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46162. case 1:
  46163. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46164. case 2:
  46165. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46166. case 3:
  46167. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46168. case 4:
  46169. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46170. case 5:
  46171. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46172. }
  46173. }
  46174. return BABYLON.Vector3.Zero();
  46175. };
  46176. /**
  46177. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46178. * - fov = PI / 2
  46179. * - aspect ratio : 1.0
  46180. * - z-near and far equal to the active camera minZ and maxZ.
  46181. * Returns the PointLight.
  46182. */
  46183. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46184. var activeCamera = this.getScene().activeCamera;
  46185. if (!activeCamera) {
  46186. return;
  46187. }
  46188. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46189. };
  46190. PointLight.prototype._buildUniformLayout = function () {
  46191. this._uniformBuffer.addUniform("vLightData", 4);
  46192. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46193. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46194. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46195. this._uniformBuffer.addUniform("depthValues", 2);
  46196. this._uniformBuffer.create();
  46197. };
  46198. /**
  46199. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46200. * @param effect The effect to update
  46201. * @param lightIndex The index of the light in the effect to update
  46202. * @returns The point light
  46203. */
  46204. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46205. if (this.computeTransformedInformation()) {
  46206. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46207. return this;
  46208. }
  46209. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46210. return this;
  46211. };
  46212. __decorate([
  46213. BABYLON.serialize()
  46214. ], PointLight.prototype, "shadowAngle", null);
  46215. return PointLight;
  46216. }(BABYLON.ShadowLight));
  46217. BABYLON.PointLight = PointLight;
  46218. })(BABYLON || (BABYLON = {}));
  46219. //# sourceMappingURL=babylon.pointLight.js.map
  46220. "use strict";
  46221. var BABYLON;
  46222. (function (BABYLON) {
  46223. /**
  46224. * A directional light is defined by a direction (what a surprise!).
  46225. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46226. * 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.
  46227. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46228. */
  46229. var DirectionalLight = /** @class */ (function (_super) {
  46230. __extends(DirectionalLight, _super);
  46231. /**
  46232. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46233. * The directional light is emitted from everywhere in the given direction.
  46234. * It can cast shawdows.
  46235. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46236. * @param name The friendly name of the light
  46237. * @param direction The direction of the light
  46238. * @param scene The scene the light belongs to
  46239. */
  46240. function DirectionalLight(name, direction, scene) {
  46241. var _this = _super.call(this, name, scene) || this;
  46242. _this._shadowFrustumSize = 0;
  46243. _this._shadowOrthoScale = 0.1;
  46244. /**
  46245. * Automatically compute the projection matrix to best fit (including all the casters)
  46246. * on each frame.
  46247. */
  46248. _this.autoUpdateExtends = true;
  46249. // Cache
  46250. _this._orthoLeft = Number.MAX_VALUE;
  46251. _this._orthoRight = Number.MIN_VALUE;
  46252. _this._orthoTop = Number.MIN_VALUE;
  46253. _this._orthoBottom = Number.MAX_VALUE;
  46254. _this.position = direction.scale(-1.0);
  46255. _this.direction = direction;
  46256. return _this;
  46257. }
  46258. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46259. /**
  46260. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46261. */
  46262. get: function () {
  46263. return this._shadowFrustumSize;
  46264. },
  46265. /**
  46266. * Specifies a fix frustum size for the shadow generation.
  46267. */
  46268. set: function (value) {
  46269. this._shadowFrustumSize = value;
  46270. this.forceProjectionMatrixCompute();
  46271. },
  46272. enumerable: true,
  46273. configurable: true
  46274. });
  46275. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46276. /**
  46277. * Gets the shadow projection scale against the optimal computed one.
  46278. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46279. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46280. */
  46281. get: function () {
  46282. return this._shadowOrthoScale;
  46283. },
  46284. /**
  46285. * Sets the shadow projection scale against the optimal computed one.
  46286. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46287. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46288. */
  46289. set: function (value) {
  46290. this._shadowOrthoScale = value;
  46291. this.forceProjectionMatrixCompute();
  46292. },
  46293. enumerable: true,
  46294. configurable: true
  46295. });
  46296. /**
  46297. * Returns the string "DirectionalLight".
  46298. * @return The class name
  46299. */
  46300. DirectionalLight.prototype.getClassName = function () {
  46301. return "DirectionalLight";
  46302. };
  46303. /**
  46304. * Returns the integer 1.
  46305. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46306. */
  46307. DirectionalLight.prototype.getTypeID = function () {
  46308. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46309. };
  46310. /**
  46311. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46312. * Returns the DirectionalLight Shadow projection matrix.
  46313. */
  46314. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46315. if (this.shadowFrustumSize > 0) {
  46316. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46317. }
  46318. else {
  46319. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46320. }
  46321. };
  46322. /**
  46323. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46324. * Returns the DirectionalLight Shadow projection matrix.
  46325. */
  46326. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46327. var activeCamera = this.getScene().activeCamera;
  46328. if (!activeCamera) {
  46329. return;
  46330. }
  46331. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46332. };
  46333. /**
  46334. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46335. * Returns the DirectionalLight Shadow projection matrix.
  46336. */
  46337. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46338. var activeCamera = this.getScene().activeCamera;
  46339. if (!activeCamera) {
  46340. return;
  46341. }
  46342. // Check extends
  46343. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46344. var tempVector3 = BABYLON.Vector3.Zero();
  46345. this._orthoLeft = Number.MAX_VALUE;
  46346. this._orthoRight = Number.MIN_VALUE;
  46347. this._orthoTop = Number.MIN_VALUE;
  46348. this._orthoBottom = Number.MAX_VALUE;
  46349. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46350. var mesh = renderList[meshIndex];
  46351. if (!mesh) {
  46352. continue;
  46353. }
  46354. var boundingInfo = mesh.getBoundingInfo();
  46355. var boundingBox = boundingInfo.boundingBox;
  46356. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46357. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46358. if (tempVector3.x < this._orthoLeft)
  46359. this._orthoLeft = tempVector3.x;
  46360. if (tempVector3.y < this._orthoBottom)
  46361. this._orthoBottom = tempVector3.y;
  46362. if (tempVector3.x > this._orthoRight)
  46363. this._orthoRight = tempVector3.x;
  46364. if (tempVector3.y > this._orthoTop)
  46365. this._orthoTop = tempVector3.y;
  46366. }
  46367. }
  46368. }
  46369. var xOffset = this._orthoRight - this._orthoLeft;
  46370. var yOffset = this._orthoTop - this._orthoBottom;
  46371. 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);
  46372. };
  46373. DirectionalLight.prototype._buildUniformLayout = function () {
  46374. this._uniformBuffer.addUniform("vLightData", 4);
  46375. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46376. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46377. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46378. this._uniformBuffer.addUniform("depthValues", 2);
  46379. this._uniformBuffer.create();
  46380. };
  46381. /**
  46382. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46383. * @param effect The effect to update
  46384. * @param lightIndex The index of the light in the effect to update
  46385. * @returns The directional light
  46386. */
  46387. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46388. if (this.computeTransformedInformation()) {
  46389. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46390. return this;
  46391. }
  46392. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46393. return this;
  46394. };
  46395. /**
  46396. * Gets the minZ used for shadow according to both the scene and the light.
  46397. *
  46398. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46399. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46400. * @param activeCamera The camera we are returning the min for
  46401. * @returns the depth min z
  46402. */
  46403. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46404. return 1;
  46405. };
  46406. /**
  46407. * Gets the maxZ used for shadow according to both the scene and the light.
  46408. *
  46409. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46410. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46411. * @param activeCamera The camera we are returning the max for
  46412. * @returns the depth max z
  46413. */
  46414. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46415. return 1;
  46416. };
  46417. __decorate([
  46418. BABYLON.serialize()
  46419. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46420. __decorate([
  46421. BABYLON.serialize()
  46422. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46423. __decorate([
  46424. BABYLON.serialize()
  46425. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46426. return DirectionalLight;
  46427. }(BABYLON.ShadowLight));
  46428. BABYLON.DirectionalLight = DirectionalLight;
  46429. })(BABYLON || (BABYLON = {}));
  46430. //# sourceMappingURL=babylon.directionalLight.js.map
  46431. "use strict";
  46432. var BABYLON;
  46433. (function (BABYLON) {
  46434. /**
  46435. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46436. * These values define a cone of light starting from the position, emitting toward the direction.
  46437. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46438. * and the exponent defines the speed of the decay of the light with distance (reach).
  46439. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46440. */
  46441. var SpotLight = /** @class */ (function (_super) {
  46442. __extends(SpotLight, _super);
  46443. /**
  46444. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46445. * It can cast shadows.
  46446. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46447. * @param name The light friendly name
  46448. * @param position The position of the spot light in the scene
  46449. * @param direction The direction of the light in the scene
  46450. * @param angle The cone angle of the light in Radians
  46451. * @param exponent The light decay speed with the distance from the emission spot
  46452. * @param scene The scene the lights belongs to
  46453. */
  46454. function SpotLight(name, position, direction, angle, exponent, scene) {
  46455. var _this = _super.call(this, name, scene) || this;
  46456. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46457. _this._projectionTextureLightNear = 1e-6;
  46458. _this._projectionTextureLightFar = 1000.0;
  46459. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46460. _this._projectionTextureViewLightDirty = true;
  46461. _this._projectionTextureProjectionLightDirty = true;
  46462. _this._projectionTextureDirty = true;
  46463. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46464. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46465. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46466. _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);
  46467. _this.position = position;
  46468. _this.direction = direction;
  46469. _this.angle = angle;
  46470. _this.exponent = exponent;
  46471. return _this;
  46472. }
  46473. Object.defineProperty(SpotLight.prototype, "angle", {
  46474. /**
  46475. * Gets the cone angle of the spot light in Radians.
  46476. */
  46477. get: function () {
  46478. return this._angle;
  46479. },
  46480. /**
  46481. * Sets the cone angle of the spot light in Radians.
  46482. */
  46483. set: function (value) {
  46484. this._angle = value;
  46485. this._projectionTextureProjectionLightDirty = true;
  46486. this.forceProjectionMatrixCompute();
  46487. },
  46488. enumerable: true,
  46489. configurable: true
  46490. });
  46491. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46492. /**
  46493. * Allows scaling the angle of the light for shadow generation only.
  46494. */
  46495. get: function () {
  46496. return this._shadowAngleScale;
  46497. },
  46498. /**
  46499. * Allows scaling the angle of the light for shadow generation only.
  46500. */
  46501. set: function (value) {
  46502. this._shadowAngleScale = value;
  46503. this.forceProjectionMatrixCompute();
  46504. },
  46505. enumerable: true,
  46506. configurable: true
  46507. });
  46508. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46509. /**
  46510. * Allows reading the projecton texture
  46511. */
  46512. get: function () {
  46513. return this._projectionTextureMatrix;
  46514. },
  46515. enumerable: true,
  46516. configurable: true
  46517. });
  46518. ;
  46519. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46520. /**
  46521. * Gets the near clip of the Spotlight for texture projection.
  46522. */
  46523. get: function () {
  46524. return this._projectionTextureLightNear;
  46525. },
  46526. /**
  46527. * Sets the near clip of the Spotlight for texture projection.
  46528. */
  46529. set: function (value) {
  46530. this._projectionTextureLightNear = value;
  46531. this._projectionTextureProjectionLightDirty = true;
  46532. },
  46533. enumerable: true,
  46534. configurable: true
  46535. });
  46536. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46537. /**
  46538. * Gets the far clip of the Spotlight for texture projection.
  46539. */
  46540. get: function () {
  46541. return this._projectionTextureLightFar;
  46542. },
  46543. /**
  46544. * Sets the far clip of the Spotlight for texture projection.
  46545. */
  46546. set: function (value) {
  46547. this._projectionTextureLightFar = value;
  46548. this._projectionTextureProjectionLightDirty = true;
  46549. },
  46550. enumerable: true,
  46551. configurable: true
  46552. });
  46553. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46554. /**
  46555. * Gets the Up vector of the Spotlight for texture projection.
  46556. */
  46557. get: function () {
  46558. return this._projectionTextureUpDirection;
  46559. },
  46560. /**
  46561. * Sets the Up vector of the Spotlight for texture projection.
  46562. */
  46563. set: function (value) {
  46564. this._projectionTextureUpDirection = value;
  46565. this._projectionTextureProjectionLightDirty = true;
  46566. },
  46567. enumerable: true,
  46568. configurable: true
  46569. });
  46570. ;
  46571. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46572. /**
  46573. * Gets the projection texture of the light.
  46574. */
  46575. get: function () {
  46576. return this._projectionTexture;
  46577. },
  46578. /**
  46579. * Sets the projection texture of the light.
  46580. */
  46581. set: function (value) {
  46582. this._projectionTexture = value;
  46583. this._projectionTextureDirty = true;
  46584. },
  46585. enumerable: true,
  46586. configurable: true
  46587. });
  46588. /**
  46589. * Returns the string "SpotLight".
  46590. * @returns the class name
  46591. */
  46592. SpotLight.prototype.getClassName = function () {
  46593. return "SpotLight";
  46594. };
  46595. /**
  46596. * Returns the integer 2.
  46597. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46598. */
  46599. SpotLight.prototype.getTypeID = function () {
  46600. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46601. };
  46602. /**
  46603. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46604. */
  46605. SpotLight.prototype._setDirection = function (value) {
  46606. _super.prototype._setDirection.call(this, value);
  46607. this._projectionTextureViewLightDirty = true;
  46608. };
  46609. /**
  46610. * Overrides the position setter to recompute the projection texture view light Matrix.
  46611. */
  46612. SpotLight.prototype._setPosition = function (value) {
  46613. _super.prototype._setPosition.call(this, value);
  46614. this._projectionTextureViewLightDirty = true;
  46615. };
  46616. /**
  46617. * 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.
  46618. * Returns the SpotLight.
  46619. */
  46620. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46621. var activeCamera = this.getScene().activeCamera;
  46622. if (!activeCamera) {
  46623. return;
  46624. }
  46625. this._shadowAngleScale = this._shadowAngleScale || 1;
  46626. var angle = this._shadowAngleScale * this._angle;
  46627. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46628. };
  46629. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46630. this._projectionTextureViewLightDirty = false;
  46631. this._projectionTextureDirty = true;
  46632. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46633. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46634. };
  46635. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46636. this._projectionTextureProjectionLightDirty = false;
  46637. this._projectionTextureDirty = true;
  46638. var light_far = this.projectionTextureLightFar;
  46639. var light_near = this.projectionTextureLightNear;
  46640. var P = light_far / (light_far - light_near);
  46641. var Q = -P * light_near;
  46642. var S = 1.0 / Math.tan(this._angle / 2.0);
  46643. var A = 1.0;
  46644. 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);
  46645. };
  46646. /**
  46647. * Main function for light texture projection matrix computing.
  46648. */
  46649. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46650. this._projectionTextureDirty = false;
  46651. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46652. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46653. };
  46654. SpotLight.prototype._buildUniformLayout = function () {
  46655. this._uniformBuffer.addUniform("vLightData", 4);
  46656. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46657. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46658. this._uniformBuffer.addUniform("vLightDirection", 3);
  46659. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46660. this._uniformBuffer.addUniform("depthValues", 2);
  46661. this._uniformBuffer.create();
  46662. };
  46663. /**
  46664. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46665. * @param effect The effect to update
  46666. * @param lightIndex The index of the light in the effect to update
  46667. * @returns The spot light
  46668. */
  46669. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46670. var normalizeDirection;
  46671. if (this.computeTransformedInformation()) {
  46672. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46673. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46674. }
  46675. else {
  46676. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46677. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46678. }
  46679. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46680. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46681. if (this._projectionTextureViewLightDirty) {
  46682. this._computeProjectionTextureViewLightMatrix();
  46683. }
  46684. if (this._projectionTextureProjectionLightDirty) {
  46685. this._computeProjectionTextureProjectionLightMatrix();
  46686. }
  46687. if (this._projectionTextureDirty) {
  46688. this._computeProjectionTextureMatrix();
  46689. }
  46690. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46691. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46692. }
  46693. return this;
  46694. };
  46695. /**
  46696. * Disposes the light and the associated resources.
  46697. */
  46698. SpotLight.prototype.dispose = function () {
  46699. _super.prototype.dispose.call(this);
  46700. if (this._projectionTexture) {
  46701. this._projectionTexture.dispose();
  46702. }
  46703. };
  46704. __decorate([
  46705. BABYLON.serialize()
  46706. ], SpotLight.prototype, "angle", null);
  46707. __decorate([
  46708. BABYLON.serialize()
  46709. ], SpotLight.prototype, "shadowAngleScale", null);
  46710. __decorate([
  46711. BABYLON.serialize()
  46712. ], SpotLight.prototype, "exponent", void 0);
  46713. __decorate([
  46714. BABYLON.serialize()
  46715. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46716. __decorate([
  46717. BABYLON.serialize()
  46718. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46719. __decorate([
  46720. BABYLON.serialize()
  46721. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46722. __decorate([
  46723. BABYLON.serializeAsTexture("projectedLightTexture")
  46724. ], SpotLight.prototype, "_projectionTexture", void 0);
  46725. return SpotLight;
  46726. }(BABYLON.ShadowLight));
  46727. BABYLON.SpotLight = SpotLight;
  46728. })(BABYLON || (BABYLON = {}));
  46729. //# sourceMappingURL=babylon.spotLight.js.map
  46730. "use strict";
  46731. var BABYLON;
  46732. (function (BABYLON) {
  46733. /**
  46734. * Class used to override all child animations of a given target
  46735. */
  46736. var AnimationPropertiesOverride = /** @class */ (function () {
  46737. function AnimationPropertiesOverride() {
  46738. /**
  46739. * Gets or sets a value indicating if animation blending must be used
  46740. */
  46741. this.enableBlending = false;
  46742. /**
  46743. * Gets or sets the blending speed to use when enableBlending is true
  46744. */
  46745. this.blendingSpeed = 0.01;
  46746. /**
  46747. * Gets or sets the default loop mode to use
  46748. */
  46749. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46750. }
  46751. return AnimationPropertiesOverride;
  46752. }());
  46753. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46754. })(BABYLON || (BABYLON = {}));
  46755. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46756. "use strict";
  46757. var BABYLON;
  46758. (function (BABYLON) {
  46759. var AnimationRange = /** @class */ (function () {
  46760. function AnimationRange(name, from, to) {
  46761. this.name = name;
  46762. this.from = from;
  46763. this.to = to;
  46764. }
  46765. AnimationRange.prototype.clone = function () {
  46766. return new AnimationRange(this.name, this.from, this.to);
  46767. };
  46768. return AnimationRange;
  46769. }());
  46770. BABYLON.AnimationRange = AnimationRange;
  46771. /**
  46772. * Composed of a frame, and an action function
  46773. */
  46774. var AnimationEvent = /** @class */ (function () {
  46775. function AnimationEvent(frame, action, onlyOnce) {
  46776. this.frame = frame;
  46777. this.action = action;
  46778. this.onlyOnce = onlyOnce;
  46779. this.isDone = false;
  46780. }
  46781. return AnimationEvent;
  46782. }());
  46783. BABYLON.AnimationEvent = AnimationEvent;
  46784. var PathCursor = /** @class */ (function () {
  46785. function PathCursor(path) {
  46786. this.path = path;
  46787. this._onchange = new Array();
  46788. this.value = 0;
  46789. this.animations = new Array();
  46790. }
  46791. PathCursor.prototype.getPoint = function () {
  46792. var point = this.path.getPointAtLengthPosition(this.value);
  46793. return new BABYLON.Vector3(point.x, 0, point.y);
  46794. };
  46795. PathCursor.prototype.moveAhead = function (step) {
  46796. if (step === void 0) { step = 0.002; }
  46797. this.move(step);
  46798. return this;
  46799. };
  46800. PathCursor.prototype.moveBack = function (step) {
  46801. if (step === void 0) { step = 0.002; }
  46802. this.move(-step);
  46803. return this;
  46804. };
  46805. PathCursor.prototype.move = function (step) {
  46806. if (Math.abs(step) > 1) {
  46807. throw "step size should be less than 1.";
  46808. }
  46809. this.value += step;
  46810. this.ensureLimits();
  46811. this.raiseOnChange();
  46812. return this;
  46813. };
  46814. PathCursor.prototype.ensureLimits = function () {
  46815. while (this.value > 1) {
  46816. this.value -= 1;
  46817. }
  46818. while (this.value < 0) {
  46819. this.value += 1;
  46820. }
  46821. return this;
  46822. };
  46823. // used by animation engine
  46824. PathCursor.prototype.raiseOnChange = function () {
  46825. var _this = this;
  46826. this._onchange.forEach(function (f) { return f(_this); });
  46827. return this;
  46828. };
  46829. PathCursor.prototype.onchange = function (f) {
  46830. this._onchange.push(f);
  46831. return this;
  46832. };
  46833. return PathCursor;
  46834. }());
  46835. BABYLON.PathCursor = PathCursor;
  46836. var AnimationKeyInterpolation;
  46837. (function (AnimationKeyInterpolation) {
  46838. /**
  46839. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46840. */
  46841. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46842. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46843. var Animation = /** @class */ (function () {
  46844. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46845. this.name = name;
  46846. this.targetProperty = targetProperty;
  46847. this.framePerSecond = framePerSecond;
  46848. this.dataType = dataType;
  46849. this.loopMode = loopMode;
  46850. this.enableBlending = enableBlending;
  46851. this._runtimeAnimations = new Array();
  46852. // The set of event that will be linked to this animation
  46853. this._events = new Array();
  46854. this.blendingSpeed = 0.01;
  46855. this._ranges = {};
  46856. this.targetPropertyPath = targetProperty.split(".");
  46857. this.dataType = dataType;
  46858. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46859. }
  46860. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46861. var dataType = undefined;
  46862. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46863. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46864. }
  46865. else if (from instanceof BABYLON.Quaternion) {
  46866. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46867. }
  46868. else if (from instanceof BABYLON.Vector3) {
  46869. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46870. }
  46871. else if (from instanceof BABYLON.Vector2) {
  46872. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46873. }
  46874. else if (from instanceof BABYLON.Color3) {
  46875. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46876. }
  46877. else if (from instanceof BABYLON.Size) {
  46878. dataType = Animation.ANIMATIONTYPE_SIZE;
  46879. }
  46880. if (dataType == undefined) {
  46881. return null;
  46882. }
  46883. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46884. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46885. animation.setKeys(keys);
  46886. if (easingFunction !== undefined) {
  46887. animation.setEasingFunction(easingFunction);
  46888. }
  46889. return animation;
  46890. };
  46891. /**
  46892. * Sets up an animation.
  46893. * @param property the property to animate
  46894. * @param animationType the animation type to apply
  46895. * @param easingFunction the easing function used in the animation
  46896. * @returns The created animation
  46897. */
  46898. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46899. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46900. animation.setEasingFunction(easingFunction);
  46901. return animation;
  46902. };
  46903. /**
  46904. * Create and start an animation on a node
  46905. * @param {string} name defines the name of the global animation that will be run on all nodes
  46906. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46907. * @param {string} targetProperty defines property to animate
  46908. * @param {number} framePerSecond defines the number of frame per second yo use
  46909. * @param {number} totalFrame defines the number of frames in total
  46910. * @param {any} from defines the initial value
  46911. * @param {any} to defines the final value
  46912. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46913. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46914. * @param onAnimationEnd defines the callback to call when animation end
  46915. * @returns the animatable created for this animation
  46916. */
  46917. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46918. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46919. if (!animation) {
  46920. return null;
  46921. }
  46922. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46923. };
  46924. /**
  46925. * Create and start an animation on a node and its descendants
  46926. * @param {string} name defines the name of the global animation that will be run on all nodes
  46927. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46928. * @param {boolean} 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.
  46929. * @param {string} targetProperty defines property to animate
  46930. * @param {number} framePerSecond defines the number of frame per second yo use
  46931. * @param {number} totalFrame defines the number of frames in total
  46932. * @param {any} from defines the initial value
  46933. * @param {any} to defines the final value
  46934. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46935. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46936. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46937. * @returns the list of animatables created for all nodes
  46938. * @example https://www.babylonjs-playground.com/#MH0VLI
  46939. */
  46940. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46941. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46942. if (!animation) {
  46943. return null;
  46944. }
  46945. var scene = node.getScene();
  46946. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46947. };
  46948. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46949. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46950. if (!animation) {
  46951. return null;
  46952. }
  46953. node.animations.push(animation);
  46954. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46955. };
  46956. /**
  46957. * Transition property of the Camera to the target Value.
  46958. * @param property The property to transition
  46959. * @param targetValue The target Value of the property
  46960. * @param host The object where the property to animate belongs
  46961. * @param scene Scene used to run the animation
  46962. * @param frameRate Framerate (in frame/s) to use
  46963. * @param transition The transition type we want to use
  46964. * @param duration The duration of the animation, in milliseconds
  46965. * @param onAnimationEnd Call back trigger at the end of the animation.
  46966. */
  46967. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46968. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46969. if (duration <= 0) {
  46970. host[property] = targetValue;
  46971. if (onAnimationEnd) {
  46972. onAnimationEnd();
  46973. }
  46974. return null;
  46975. }
  46976. var endFrame = frameRate * (duration / 1000);
  46977. transition.setKeys([{
  46978. frame: 0,
  46979. value: host[property].clone ? host[property].clone() : host[property]
  46980. },
  46981. {
  46982. frame: endFrame,
  46983. value: targetValue
  46984. }]);
  46985. if (!host.animations) {
  46986. host.animations = [];
  46987. }
  46988. host.animations.push(transition);
  46989. var animation = scene.beginAnimation(host, 0, endFrame, false);
  46990. animation.onAnimationEnd = onAnimationEnd;
  46991. return animation;
  46992. };
  46993. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  46994. /**
  46995. * Return the array of runtime animations currently using this animation
  46996. */
  46997. get: function () {
  46998. return this._runtimeAnimations;
  46999. },
  47000. enumerable: true,
  47001. configurable: true
  47002. });
  47003. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47004. get: function () {
  47005. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47006. var runtimeAnimation = _a[_i];
  47007. if (!runtimeAnimation.isStopped) {
  47008. return true;
  47009. }
  47010. }
  47011. return false;
  47012. },
  47013. enumerable: true,
  47014. configurable: true
  47015. });
  47016. // Methods
  47017. /**
  47018. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47019. */
  47020. Animation.prototype.toString = function (fullDetails) {
  47021. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47022. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47023. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47024. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47025. if (fullDetails) {
  47026. ret += ", Ranges: {";
  47027. var first = true;
  47028. for (var name in this._ranges) {
  47029. if (first) {
  47030. ret += ", ";
  47031. first = false;
  47032. }
  47033. ret += name;
  47034. }
  47035. ret += "}";
  47036. }
  47037. return ret;
  47038. };
  47039. /**
  47040. * Add an event to this animation.
  47041. */
  47042. Animation.prototype.addEvent = function (event) {
  47043. this._events.push(event);
  47044. };
  47045. /**
  47046. * Remove all events found at the given frame
  47047. * @param frame
  47048. */
  47049. Animation.prototype.removeEvents = function (frame) {
  47050. for (var index = 0; index < this._events.length; index++) {
  47051. if (this._events[index].frame === frame) {
  47052. this._events.splice(index, 1);
  47053. index--;
  47054. }
  47055. }
  47056. };
  47057. Animation.prototype.getEvents = function () {
  47058. return this._events;
  47059. };
  47060. Animation.prototype.createRange = function (name, from, to) {
  47061. // check name not already in use; could happen for bones after serialized
  47062. if (!this._ranges[name]) {
  47063. this._ranges[name] = new AnimationRange(name, from, to);
  47064. }
  47065. };
  47066. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47067. if (deleteFrames === void 0) { deleteFrames = true; }
  47068. var range = this._ranges[name];
  47069. if (!range) {
  47070. return;
  47071. }
  47072. if (deleteFrames) {
  47073. var from = range.from;
  47074. var to = range.to;
  47075. // this loop MUST go high to low for multiple splices to work
  47076. for (var key = this._keys.length - 1; key >= 0; key--) {
  47077. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47078. this._keys.splice(key, 1);
  47079. }
  47080. }
  47081. }
  47082. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47083. };
  47084. Animation.prototype.getRange = function (name) {
  47085. return this._ranges[name];
  47086. };
  47087. Animation.prototype.getKeys = function () {
  47088. return this._keys;
  47089. };
  47090. Animation.prototype.getHighestFrame = function () {
  47091. var ret = 0;
  47092. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47093. if (ret < this._keys[key].frame) {
  47094. ret = this._keys[key].frame;
  47095. }
  47096. }
  47097. return ret;
  47098. };
  47099. Animation.prototype.getEasingFunction = function () {
  47100. return this._easingFunction;
  47101. };
  47102. Animation.prototype.setEasingFunction = function (easingFunction) {
  47103. this._easingFunction = easingFunction;
  47104. };
  47105. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47106. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47107. };
  47108. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47109. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47110. };
  47111. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47112. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47113. };
  47114. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47115. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47116. };
  47117. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47118. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47119. };
  47120. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47121. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47122. };
  47123. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47124. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47125. };
  47126. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47127. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47128. };
  47129. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47130. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47131. };
  47132. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47133. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47134. };
  47135. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47136. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47137. };
  47138. Animation.prototype.clone = function () {
  47139. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47140. clone.enableBlending = this.enableBlending;
  47141. clone.blendingSpeed = this.blendingSpeed;
  47142. if (this._keys) {
  47143. clone.setKeys(this._keys);
  47144. }
  47145. if (this._ranges) {
  47146. clone._ranges = {};
  47147. for (var name in this._ranges) {
  47148. var range = this._ranges[name];
  47149. if (!range) {
  47150. continue;
  47151. }
  47152. clone._ranges[name] = range.clone();
  47153. }
  47154. }
  47155. return clone;
  47156. };
  47157. Animation.prototype.setKeys = function (values) {
  47158. this._keys = values.slice(0);
  47159. };
  47160. Animation.prototype.serialize = function () {
  47161. var serializationObject = {};
  47162. serializationObject.name = this.name;
  47163. serializationObject.property = this.targetProperty;
  47164. serializationObject.framePerSecond = this.framePerSecond;
  47165. serializationObject.dataType = this.dataType;
  47166. serializationObject.loopBehavior = this.loopMode;
  47167. serializationObject.enableBlending = this.enableBlending;
  47168. serializationObject.blendingSpeed = this.blendingSpeed;
  47169. var dataType = this.dataType;
  47170. serializationObject.keys = [];
  47171. var keys = this.getKeys();
  47172. for (var index = 0; index < keys.length; index++) {
  47173. var animationKey = keys[index];
  47174. var key = {};
  47175. key.frame = animationKey.frame;
  47176. switch (dataType) {
  47177. case Animation.ANIMATIONTYPE_FLOAT:
  47178. key.values = [animationKey.value];
  47179. break;
  47180. case Animation.ANIMATIONTYPE_QUATERNION:
  47181. case Animation.ANIMATIONTYPE_MATRIX:
  47182. case Animation.ANIMATIONTYPE_VECTOR3:
  47183. case Animation.ANIMATIONTYPE_COLOR3:
  47184. key.values = animationKey.value.asArray();
  47185. break;
  47186. }
  47187. serializationObject.keys.push(key);
  47188. }
  47189. serializationObject.ranges = [];
  47190. for (var name in this._ranges) {
  47191. var source = this._ranges[name];
  47192. if (!source) {
  47193. continue;
  47194. }
  47195. var range = {};
  47196. range.name = name;
  47197. range.from = source.from;
  47198. range.to = source.to;
  47199. serializationObject.ranges.push(range);
  47200. }
  47201. return serializationObject;
  47202. };
  47203. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47204. get: function () {
  47205. return Animation._ANIMATIONTYPE_FLOAT;
  47206. },
  47207. enumerable: true,
  47208. configurable: true
  47209. });
  47210. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47211. get: function () {
  47212. return Animation._ANIMATIONTYPE_VECTOR3;
  47213. },
  47214. enumerable: true,
  47215. configurable: true
  47216. });
  47217. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47218. get: function () {
  47219. return Animation._ANIMATIONTYPE_VECTOR2;
  47220. },
  47221. enumerable: true,
  47222. configurable: true
  47223. });
  47224. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47225. get: function () {
  47226. return Animation._ANIMATIONTYPE_SIZE;
  47227. },
  47228. enumerable: true,
  47229. configurable: true
  47230. });
  47231. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47232. get: function () {
  47233. return Animation._ANIMATIONTYPE_QUATERNION;
  47234. },
  47235. enumerable: true,
  47236. configurable: true
  47237. });
  47238. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47239. get: function () {
  47240. return Animation._ANIMATIONTYPE_MATRIX;
  47241. },
  47242. enumerable: true,
  47243. configurable: true
  47244. });
  47245. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47246. get: function () {
  47247. return Animation._ANIMATIONTYPE_COLOR3;
  47248. },
  47249. enumerable: true,
  47250. configurable: true
  47251. });
  47252. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47253. get: function () {
  47254. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47255. },
  47256. enumerable: true,
  47257. configurable: true
  47258. });
  47259. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47260. get: function () {
  47261. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47262. },
  47263. enumerable: true,
  47264. configurable: true
  47265. });
  47266. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47267. get: function () {
  47268. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Animation.Parse = function (parsedAnimation) {
  47274. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47275. var dataType = parsedAnimation.dataType;
  47276. var keys = [];
  47277. var data;
  47278. var index;
  47279. if (parsedAnimation.enableBlending) {
  47280. animation.enableBlending = parsedAnimation.enableBlending;
  47281. }
  47282. if (parsedAnimation.blendingSpeed) {
  47283. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47284. }
  47285. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47286. var key = parsedAnimation.keys[index];
  47287. var inTangent;
  47288. var outTangent;
  47289. switch (dataType) {
  47290. case Animation.ANIMATIONTYPE_FLOAT:
  47291. data = key.values[0];
  47292. if (key.values.length >= 1) {
  47293. inTangent = key.values[1];
  47294. }
  47295. if (key.values.length >= 2) {
  47296. outTangent = key.values[2];
  47297. }
  47298. break;
  47299. case Animation.ANIMATIONTYPE_QUATERNION:
  47300. data = BABYLON.Quaternion.FromArray(key.values);
  47301. if (key.values.length >= 8) {
  47302. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47303. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47304. inTangent = _inTangent;
  47305. }
  47306. }
  47307. if (key.values.length >= 12) {
  47308. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47309. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47310. outTangent = _outTangent;
  47311. }
  47312. }
  47313. break;
  47314. case Animation.ANIMATIONTYPE_MATRIX:
  47315. data = BABYLON.Matrix.FromArray(key.values);
  47316. break;
  47317. case Animation.ANIMATIONTYPE_COLOR3:
  47318. data = BABYLON.Color3.FromArray(key.values);
  47319. break;
  47320. case Animation.ANIMATIONTYPE_VECTOR3:
  47321. default:
  47322. data = BABYLON.Vector3.FromArray(key.values);
  47323. break;
  47324. }
  47325. var keyData = {};
  47326. keyData.frame = key.frame;
  47327. keyData.value = data;
  47328. if (inTangent != undefined) {
  47329. keyData.inTangent = inTangent;
  47330. }
  47331. if (outTangent != undefined) {
  47332. keyData.outTangent = outTangent;
  47333. }
  47334. keys.push(keyData);
  47335. }
  47336. animation.setKeys(keys);
  47337. if (parsedAnimation.ranges) {
  47338. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47339. data = parsedAnimation.ranges[index];
  47340. animation.createRange(data.name, data.from, data.to);
  47341. }
  47342. }
  47343. return animation;
  47344. };
  47345. Animation.AppendSerializedAnimations = function (source, destination) {
  47346. if (source.animations) {
  47347. destination.animations = [];
  47348. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47349. var animation = source.animations[animationIndex];
  47350. destination.animations.push(animation.serialize());
  47351. }
  47352. }
  47353. };
  47354. Animation.AllowMatricesInterpolation = false;
  47355. // Statics
  47356. Animation._ANIMATIONTYPE_FLOAT = 0;
  47357. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47358. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47359. Animation._ANIMATIONTYPE_MATRIX = 3;
  47360. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47361. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47362. Animation._ANIMATIONTYPE_SIZE = 6;
  47363. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47364. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47365. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47366. return Animation;
  47367. }());
  47368. BABYLON.Animation = Animation;
  47369. })(BABYLON || (BABYLON = {}));
  47370. //# sourceMappingURL=babylon.animation.js.map
  47371. "use strict";
  47372. var BABYLON;
  47373. (function (BABYLON) {
  47374. /**
  47375. * This class defines the direct association between an animation and a target
  47376. */
  47377. var TargetedAnimation = /** @class */ (function () {
  47378. function TargetedAnimation() {
  47379. }
  47380. return TargetedAnimation;
  47381. }());
  47382. BABYLON.TargetedAnimation = TargetedAnimation;
  47383. /**
  47384. * Use this class to create coordinated animations on multiple targets
  47385. */
  47386. var AnimationGroup = /** @class */ (function () {
  47387. function AnimationGroup(name, scene) {
  47388. if (scene === void 0) { scene = null; }
  47389. this.name = name;
  47390. this._targetedAnimations = new Array();
  47391. this._animatables = new Array();
  47392. this._from = Number.MAX_VALUE;
  47393. this._to = -Number.MAX_VALUE;
  47394. this._speedRatio = 1;
  47395. this.onAnimationEndObservable = new BABYLON.Observable();
  47396. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47397. this._scene.animationGroups.push(this);
  47398. }
  47399. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47400. /**
  47401. * Define if the animations are started
  47402. */
  47403. get: function () {
  47404. return this._isStarted;
  47405. },
  47406. enumerable: true,
  47407. configurable: true
  47408. });
  47409. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47410. /**
  47411. * Gets or sets the speed ratio to use for all animations
  47412. */
  47413. get: function () {
  47414. return this._speedRatio;
  47415. },
  47416. /**
  47417. * Gets or sets the speed ratio to use for all animations
  47418. */
  47419. set: function (value) {
  47420. if (this._speedRatio === value) {
  47421. return;
  47422. }
  47423. this._speedRatio = value;
  47424. for (var index = 0; index < this._animatables.length; index++) {
  47425. var animatable = this._animatables[index];
  47426. animatable.speedRatio = this._speedRatio;
  47427. }
  47428. },
  47429. enumerable: true,
  47430. configurable: true
  47431. });
  47432. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47433. /**
  47434. * Gets the targeted animations for this animation group
  47435. */
  47436. get: function () {
  47437. return this._targetedAnimations;
  47438. },
  47439. enumerable: true,
  47440. configurable: true
  47441. });
  47442. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47443. /**
  47444. * returning the list of animatables controlled by this animation group.
  47445. */
  47446. get: function () {
  47447. return this._animatables;
  47448. },
  47449. enumerable: true,
  47450. configurable: true
  47451. });
  47452. /**
  47453. * Add an animation (with its target) in the group
  47454. * @param animation defines the animation we want to add
  47455. * @param target defines the target of the animation
  47456. * @returns the {BABYLON.TargetedAnimation} object
  47457. */
  47458. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47459. var targetedAnimation = {
  47460. animation: animation,
  47461. target: target
  47462. };
  47463. var keys = animation.getKeys();
  47464. if (this._from > keys[0].frame) {
  47465. this._from = keys[0].frame;
  47466. }
  47467. if (this._to < keys[keys.length - 1].frame) {
  47468. this._to = keys[keys.length - 1].frame;
  47469. }
  47470. this._targetedAnimations.push(targetedAnimation);
  47471. return targetedAnimation;
  47472. };
  47473. /**
  47474. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47475. * It can add constant keys at begin or end
  47476. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47477. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47478. */
  47479. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47480. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47481. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47482. beginFrame = Math.max(beginFrame, this._from);
  47483. endFrame = Math.min(endFrame, this._to);
  47484. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47485. var targetedAnimation = this._targetedAnimations[index];
  47486. var keys = targetedAnimation.animation.getKeys();
  47487. var startKey = keys[0];
  47488. var endKey = keys[keys.length - 1];
  47489. if (startKey.frame > beginFrame) {
  47490. var newKey = {
  47491. frame: beginFrame,
  47492. value: startKey.value,
  47493. inTangent: startKey.inTangent,
  47494. outTangent: startKey.outTangent,
  47495. interpolation: startKey.interpolation
  47496. };
  47497. keys.splice(0, 0, newKey);
  47498. }
  47499. if (endKey.frame < endFrame) {
  47500. var newKey = {
  47501. frame: endFrame,
  47502. value: endKey.value,
  47503. inTangent: endKey.outTangent,
  47504. outTangent: endKey.outTangent,
  47505. interpolation: endKey.interpolation
  47506. };
  47507. keys.push(newKey);
  47508. }
  47509. }
  47510. return this;
  47511. };
  47512. /**
  47513. * Start all animations on given targets
  47514. * @param loop defines if animations must loop
  47515. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47516. * @param from defines the from key (optional)
  47517. * @param to defines the to key (optional)
  47518. * @returns the current animation group
  47519. */
  47520. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  47521. var _this = this;
  47522. if (loop === void 0) { loop = false; }
  47523. if (speedRatio === void 0) { speedRatio = 1; }
  47524. if (this._isStarted || this._targetedAnimations.length === 0) {
  47525. return this;
  47526. }
  47527. var _loop_1 = function () {
  47528. var targetedAnimation = this_1._targetedAnimations[index];
  47529. if (!targetedAnimation.target.animations) {
  47530. targetedAnimation.target.animations = [];
  47531. }
  47532. if (targetedAnimation.target.animations.indexOf(targetedAnimation.animation) === -1) {
  47533. targetedAnimation.target.animations.push(targetedAnimation.animation);
  47534. }
  47535. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  47536. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47537. }));
  47538. };
  47539. var this_1 = this;
  47540. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47541. _loop_1();
  47542. }
  47543. this._speedRatio = speedRatio;
  47544. this._isStarted = true;
  47545. return this;
  47546. };
  47547. /**
  47548. * Pause all animations
  47549. */
  47550. AnimationGroup.prototype.pause = function () {
  47551. if (!this._isStarted) {
  47552. return this;
  47553. }
  47554. for (var index = 0; index < this._animatables.length; index++) {
  47555. var animatable = this._animatables[index];
  47556. animatable.pause();
  47557. }
  47558. return this;
  47559. };
  47560. /**
  47561. * Play all animations to initial state
  47562. * This function will start() the animations if they were not started or will restart() them if they were paused
  47563. * @param loop defines if animations must loop
  47564. */
  47565. AnimationGroup.prototype.play = function (loop) {
  47566. if (this.isStarted) {
  47567. if (loop !== undefined) {
  47568. for (var index = 0; index < this._animatables.length; index++) {
  47569. var animatable = this._animatables[index];
  47570. animatable.loopAnimation = loop;
  47571. }
  47572. }
  47573. this.restart();
  47574. }
  47575. else {
  47576. this.start(loop, this._speedRatio);
  47577. }
  47578. return this;
  47579. };
  47580. /**
  47581. * Reset all animations to initial state
  47582. */
  47583. AnimationGroup.prototype.reset = function () {
  47584. if (!this._isStarted) {
  47585. return this;
  47586. }
  47587. for (var index = 0; index < this._animatables.length; index++) {
  47588. var animatable = this._animatables[index];
  47589. animatable.reset();
  47590. }
  47591. return this;
  47592. };
  47593. /**
  47594. * Restart animations from key 0
  47595. */
  47596. AnimationGroup.prototype.restart = function () {
  47597. if (!this._isStarted) {
  47598. return this;
  47599. }
  47600. for (var index = 0; index < this._animatables.length; index++) {
  47601. var animatable = this._animatables[index];
  47602. animatable.restart();
  47603. }
  47604. return this;
  47605. };
  47606. /**
  47607. * Stop all animations
  47608. */
  47609. AnimationGroup.prototype.stop = function () {
  47610. if (!this._isStarted) {
  47611. return this;
  47612. }
  47613. for (var index = 0; index < this._animatables.length; index++) {
  47614. var animatable = this._animatables[index];
  47615. animatable.stop();
  47616. }
  47617. this._isStarted = false;
  47618. return this;
  47619. };
  47620. /**
  47621. * Goes to a specific frame in this animation group
  47622. *
  47623. * @param frame the frame number to go to
  47624. * @return the animationGroup
  47625. */
  47626. AnimationGroup.prototype.goToFrame = function (frame) {
  47627. if (!this._isStarted) {
  47628. return this;
  47629. }
  47630. for (var index = 0; index < this._animatables.length; index++) {
  47631. var animatable = this._animatables[index];
  47632. animatable.goToFrame(frame);
  47633. }
  47634. return this;
  47635. };
  47636. /**
  47637. * Dispose all associated resources
  47638. */
  47639. AnimationGroup.prototype.dispose = function () {
  47640. this._targetedAnimations = [];
  47641. this._animatables = [];
  47642. var index = this._scene.animationGroups.indexOf(this);
  47643. if (index > -1) {
  47644. this._scene.animationGroups.splice(index, 1);
  47645. }
  47646. };
  47647. return AnimationGroup;
  47648. }());
  47649. BABYLON.AnimationGroup = AnimationGroup;
  47650. })(BABYLON || (BABYLON = {}));
  47651. //# sourceMappingURL=babylon.animationGroup.js.map
  47652. "use strict";
  47653. var BABYLON;
  47654. (function (BABYLON) {
  47655. var RuntimeAnimation = /** @class */ (function () {
  47656. /**
  47657. * Create a new RuntimeAnimation object
  47658. * @param target defines the target of the animation
  47659. * @param animation defines the source {BABYLON.Animation} object
  47660. * @param scene defines the hosting scene
  47661. * @param host defines the initiating Animatable
  47662. */
  47663. function RuntimeAnimation(target, animation, scene, host) {
  47664. this._currentFrame = 0;
  47665. this._offsetsCache = {};
  47666. this._highLimitsCache = {};
  47667. this._stopped = false;
  47668. this._blendingFactor = 0;
  47669. this._targetPath = "";
  47670. this._weight = 1.0;
  47671. this._ratioOffset = 0;
  47672. this._previousDelay = 0;
  47673. this._previousRatio = 0;
  47674. this._animation = animation;
  47675. this._target = target;
  47676. this._scene = scene;
  47677. this._host = host;
  47678. animation._runtimeAnimations.push(this);
  47679. }
  47680. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  47681. /**
  47682. * Gets the current frame
  47683. */
  47684. get: function () {
  47685. return this._currentFrame;
  47686. },
  47687. enumerable: true,
  47688. configurable: true
  47689. });
  47690. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47691. /**
  47692. * Gets the weight of the runtime animation
  47693. */
  47694. get: function () {
  47695. return this._weight;
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47701. /**
  47702. * Gets the original value of the runtime animation
  47703. */
  47704. get: function () {
  47705. return this._originalValue;
  47706. },
  47707. enumerable: true,
  47708. configurable: true
  47709. });
  47710. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47711. /**
  47712. * Gets the current value of the runtime animation
  47713. */
  47714. get: function () {
  47715. return this._currentValue;
  47716. },
  47717. enumerable: true,
  47718. configurable: true
  47719. });
  47720. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47721. /**
  47722. * Gets the path where to store the animated value in the target
  47723. */
  47724. get: function () {
  47725. return this._targetPath;
  47726. },
  47727. enumerable: true,
  47728. configurable: true
  47729. });
  47730. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47731. /**
  47732. * Gets the actual target of the runtime animation
  47733. */
  47734. get: function () {
  47735. return this._activeTarget;
  47736. },
  47737. enumerable: true,
  47738. configurable: true
  47739. });
  47740. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47741. get: function () {
  47742. return this._animation;
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. RuntimeAnimation.prototype.reset = function () {
  47748. this._offsetsCache = {};
  47749. this._highLimitsCache = {};
  47750. this._currentFrame = 0;
  47751. this._blendingFactor = 0;
  47752. this._originalValue = null;
  47753. };
  47754. RuntimeAnimation.prototype.isStopped = function () {
  47755. return this._stopped;
  47756. };
  47757. RuntimeAnimation.prototype.dispose = function () {
  47758. var index = this._animation.runtimeAnimations.indexOf(this);
  47759. if (index > -1) {
  47760. this._animation.runtimeAnimations.splice(index, 1);
  47761. }
  47762. };
  47763. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47764. if (typeof value === "function") {
  47765. return value();
  47766. }
  47767. return value;
  47768. };
  47769. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47770. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47771. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47772. }
  47773. this._currentFrame = currentFrame;
  47774. var keys = this._animation.getKeys();
  47775. // Try to get a hash to find the right key
  47776. 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));
  47777. if (keys[startKeyIndex].frame >= currentFrame) {
  47778. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47779. startKeyIndex--;
  47780. }
  47781. }
  47782. for (var key = startKeyIndex; key < keys.length; key++) {
  47783. var endKey = keys[key + 1];
  47784. if (endKey.frame >= currentFrame) {
  47785. var startKey = keys[key];
  47786. var startValue = this._getKeyValue(startKey.value);
  47787. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47788. return startValue;
  47789. }
  47790. var endValue = this._getKeyValue(endKey.value);
  47791. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47792. var frameDelta = endKey.frame - startKey.frame;
  47793. // gradient : percent of currentFrame between the frame inf and the frame sup
  47794. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47795. // check for easingFunction and correction of gradient
  47796. var easingFunction = this._animation.getEasingFunction();
  47797. if (easingFunction != null) {
  47798. gradient = easingFunction.ease(gradient);
  47799. }
  47800. switch (this._animation.dataType) {
  47801. // Float
  47802. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47803. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47804. switch (loopMode) {
  47805. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47806. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47807. return floatValue;
  47808. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47809. return offsetValue * repeatCount + floatValue;
  47810. }
  47811. break;
  47812. // Quaternion
  47813. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47814. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47815. switch (loopMode) {
  47816. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47817. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47818. return quatValue;
  47819. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47820. return quatValue.add(offsetValue.scale(repeatCount));
  47821. }
  47822. return quatValue;
  47823. // Vector3
  47824. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47825. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47826. switch (loopMode) {
  47827. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47828. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47829. return vec3Value;
  47830. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47831. return vec3Value.add(offsetValue.scale(repeatCount));
  47832. }
  47833. // Vector2
  47834. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47835. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47836. switch (loopMode) {
  47837. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47838. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47839. return vec2Value;
  47840. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47841. return vec2Value.add(offsetValue.scale(repeatCount));
  47842. }
  47843. // Size
  47844. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47845. switch (loopMode) {
  47846. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47847. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47848. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47849. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47850. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47851. }
  47852. // Color3
  47853. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47854. switch (loopMode) {
  47855. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47856. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47857. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47858. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47859. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47860. }
  47861. // Matrix
  47862. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47863. switch (loopMode) {
  47864. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47865. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47866. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47867. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47868. }
  47869. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47870. return startValue;
  47871. }
  47872. default:
  47873. break;
  47874. }
  47875. break;
  47876. }
  47877. }
  47878. return this._getKeyValue(keys[keys.length - 1].value);
  47879. };
  47880. /**
  47881. * Affect the interpolated value to the target
  47882. * @param currentValue defines the value computed by the animation
  47883. * @param weight defines the weight to apply to this value
  47884. */
  47885. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47886. if (weight === void 0) { weight = 1.0; }
  47887. // Set value
  47888. var path;
  47889. var destination;
  47890. var targetPropertyPath = this._animation.targetPropertyPath;
  47891. if (targetPropertyPath.length > 1) {
  47892. var property = this._target[targetPropertyPath[0]];
  47893. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47894. property = property[targetPropertyPath[index]];
  47895. }
  47896. path = targetPropertyPath[targetPropertyPath.length - 1];
  47897. destination = property;
  47898. }
  47899. else {
  47900. path = targetPropertyPath[0];
  47901. destination = this._target;
  47902. }
  47903. this._targetPath = path;
  47904. this._activeTarget = destination;
  47905. this._weight = weight;
  47906. // Blending
  47907. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47908. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47909. if (enableBlending && this._blendingFactor <= 1.0) {
  47910. if (!this._originalBlendValue) {
  47911. var originalValue = destination[path];
  47912. if (originalValue.clone) {
  47913. this._originalBlendValue = originalValue.clone();
  47914. }
  47915. else {
  47916. this._originalBlendValue = originalValue;
  47917. }
  47918. }
  47919. }
  47920. if (weight !== -1.0) {
  47921. if (!this._originalValue) {
  47922. var originalValue = void 0;
  47923. if (destination.getRestPose) {
  47924. originalValue = destination.getRestPose();
  47925. }
  47926. else {
  47927. originalValue = destination[path];
  47928. }
  47929. if (originalValue.clone) {
  47930. this._originalValue = originalValue.clone();
  47931. }
  47932. else {
  47933. this._originalValue = originalValue;
  47934. }
  47935. }
  47936. }
  47937. if (enableBlending && this._blendingFactor <= 1.0) {
  47938. if (this._originalBlendValue.prototype) {
  47939. if (this._originalBlendValue.prototype.Lerp) {
  47940. this._currentValue = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  47941. }
  47942. else {
  47943. this._currentValue = currentValue;
  47944. }
  47945. }
  47946. else if (this._originalBlendValue.m) {
  47947. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  47948. }
  47949. else {
  47950. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47951. }
  47952. this._blendingFactor += blendingSpeed;
  47953. }
  47954. else {
  47955. this._currentValue = currentValue;
  47956. }
  47957. if (weight !== -1.0) {
  47958. this._scene._registerTargetForLateAnimationBinding(this);
  47959. }
  47960. else {
  47961. destination[path] = this._currentValue;
  47962. }
  47963. if (this._target.markAsDirty) {
  47964. this._target.markAsDirty(this._animation.targetProperty);
  47965. }
  47966. };
  47967. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47968. if (this._target && this._target.animationPropertiesOverride) {
  47969. return this._target.animationPropertiesOverride.loopMode;
  47970. }
  47971. return this._animation.loopMode;
  47972. };
  47973. /**
  47974. * Move the current animation to a given frame
  47975. * @param frame defines the frame to move to
  47976. */
  47977. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47978. var keys = this._animation.getKeys();
  47979. if (frame < keys[0].frame) {
  47980. frame = keys[0].frame;
  47981. }
  47982. else if (frame > keys[keys.length - 1].frame) {
  47983. frame = keys[keys.length - 1].frame;
  47984. }
  47985. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47986. this.setValue(currentValue, -1);
  47987. };
  47988. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47989. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47990. this._ratioOffset = this._previousRatio - newRatio;
  47991. };
  47992. /**
  47993. * Execute the current animation
  47994. * @param delay defines the delay to add to the current frame
  47995. * @param from defines the lower bound of the animation range
  47996. * @param to defines the upper bound of the animation range
  47997. * @param loop defines if the current animation must loop
  47998. * @param speedRatio defines the current speed ratio
  47999. * @param weight defines the weight of the animation (default is -1 so no weight)
  48000. * @returns a boolean indicating if the animation has ended
  48001. */
  48002. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  48003. if (weight === void 0) { weight = -1.0; }
  48004. var targetPropertyPath = this._animation.targetPropertyPath;
  48005. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  48006. this._stopped = true;
  48007. return false;
  48008. }
  48009. var returnValue = true;
  48010. var keys = this._animation.getKeys();
  48011. // Adding a start key at frame 0 if missing
  48012. if (keys[0].frame !== 0) {
  48013. var newKey = { frame: 0, value: keys[0].value };
  48014. keys.splice(0, 0, newKey);
  48015. }
  48016. // Check limits
  48017. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48018. from = keys[0].frame;
  48019. }
  48020. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48021. to = keys[keys.length - 1].frame;
  48022. }
  48023. //to and from cannot be the same key
  48024. if (from === to) {
  48025. if (from > keys[0].frame) {
  48026. from--;
  48027. }
  48028. else if (to < keys[keys.length - 1].frame) {
  48029. to++;
  48030. }
  48031. }
  48032. // Compute ratio
  48033. var range = to - from;
  48034. var offsetValue;
  48035. // ratio represents the frame delta between from and to
  48036. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48037. var highLimitValue = 0;
  48038. this._previousDelay = delay;
  48039. this._previousRatio = ratio;
  48040. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48041. returnValue = false;
  48042. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48043. }
  48044. else {
  48045. // Get max value if required
  48046. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48047. var keyOffset = to.toString() + from.toString();
  48048. if (!this._offsetsCache[keyOffset]) {
  48049. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48050. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48051. switch (this._animation.dataType) {
  48052. // Float
  48053. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48054. this._offsetsCache[keyOffset] = toValue - fromValue;
  48055. break;
  48056. // Quaternion
  48057. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48058. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48059. break;
  48060. // Vector3
  48061. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48062. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48063. // Vector2
  48064. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48065. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48066. // Size
  48067. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48068. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48069. // Color3
  48070. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48071. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48072. default:
  48073. break;
  48074. }
  48075. this._highLimitsCache[keyOffset] = toValue;
  48076. }
  48077. highLimitValue = this._highLimitsCache[keyOffset];
  48078. offsetValue = this._offsetsCache[keyOffset];
  48079. }
  48080. }
  48081. if (offsetValue === undefined) {
  48082. switch (this._animation.dataType) {
  48083. // Float
  48084. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48085. offsetValue = 0;
  48086. break;
  48087. // Quaternion
  48088. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48089. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48090. break;
  48091. // Vector3
  48092. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48093. offsetValue = BABYLON.Vector3.Zero();
  48094. break;
  48095. // Vector2
  48096. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48097. offsetValue = BABYLON.Vector2.Zero();
  48098. break;
  48099. // Size
  48100. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48101. offsetValue = BABYLON.Size.Zero();
  48102. break;
  48103. // Color3
  48104. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48105. offsetValue = BABYLON.Color3.Black();
  48106. }
  48107. }
  48108. // Compute value
  48109. var repeatCount = (ratio / range) >> 0;
  48110. var currentFrame = returnValue ? from + ratio % range : to;
  48111. // Need to normalize?
  48112. if (this._host && this._host.syncRoot) {
  48113. var syncRoot = this._host.syncRoot;
  48114. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  48115. currentFrame = from + (to - from) * hostNormalizedFrame;
  48116. }
  48117. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48118. // Set value
  48119. this.setValue(currentValue, weight);
  48120. // Check events
  48121. var events = this._animation.getEvents();
  48122. for (var index = 0; index < events.length; index++) {
  48123. // Make sure current frame has passed event frame and that event frame is within the current range
  48124. // Also, handle both forward and reverse animations
  48125. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48126. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48127. var event = events[index];
  48128. if (!event.isDone) {
  48129. // If event should be done only once, remove it.
  48130. if (event.onlyOnce) {
  48131. events.splice(index, 1);
  48132. index--;
  48133. }
  48134. event.isDone = true;
  48135. event.action();
  48136. } // Don't do anything if the event has already be done.
  48137. }
  48138. else if (events[index].isDone && !events[index].onlyOnce) {
  48139. // reset event, the animation is looping
  48140. events[index].isDone = false;
  48141. }
  48142. }
  48143. if (!returnValue) {
  48144. this._stopped = true;
  48145. }
  48146. return returnValue;
  48147. };
  48148. return RuntimeAnimation;
  48149. }());
  48150. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48151. })(BABYLON || (BABYLON = {}));
  48152. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48153. "use strict";
  48154. var BABYLON;
  48155. (function (BABYLON) {
  48156. var Animatable = /** @class */ (function () {
  48157. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48158. if (fromFrame === void 0) { fromFrame = 0; }
  48159. if (toFrame === void 0) { toFrame = 100; }
  48160. if (loopAnimation === void 0) { loopAnimation = false; }
  48161. if (speedRatio === void 0) { speedRatio = 1.0; }
  48162. this.target = target;
  48163. this.fromFrame = fromFrame;
  48164. this.toFrame = toFrame;
  48165. this.loopAnimation = loopAnimation;
  48166. this.onAnimationEnd = onAnimationEnd;
  48167. this._localDelayOffset = null;
  48168. this._pausedDelay = null;
  48169. this._runtimeAnimations = new Array();
  48170. this._paused = false;
  48171. this._speedRatio = 1;
  48172. this._weight = -1.0;
  48173. this.animationStarted = false;
  48174. if (animations) {
  48175. this.appendAnimations(target, animations);
  48176. }
  48177. this._speedRatio = speedRatio;
  48178. this._scene = scene;
  48179. scene._activeAnimatables.push(this);
  48180. }
  48181. Object.defineProperty(Animatable.prototype, "syncRoot", {
  48182. /**
  48183. * Gets the root Animatable used to synchronize and normalize animations
  48184. */
  48185. get: function () {
  48186. return this._syncRoot;
  48187. },
  48188. enumerable: true,
  48189. configurable: true
  48190. });
  48191. Object.defineProperty(Animatable.prototype, "masterFrame", {
  48192. /**
  48193. * Gets the current frame of the first RuntimeAnimation
  48194. * Used to synchronize Animatables
  48195. */
  48196. get: function () {
  48197. if (this._runtimeAnimations.length === 0) {
  48198. return 0;
  48199. }
  48200. return this._runtimeAnimations[0].currentFrame;
  48201. },
  48202. enumerable: true,
  48203. configurable: true
  48204. });
  48205. Object.defineProperty(Animatable.prototype, "weight", {
  48206. /**
  48207. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48208. */
  48209. get: function () {
  48210. return this._weight;
  48211. },
  48212. set: function (value) {
  48213. if (value === -1) {
  48214. this._weight = -1;
  48215. return;
  48216. }
  48217. // Else weight must be in [0, 1] range
  48218. this._weight = Math.min(Math.max(value, 0), 1.0);
  48219. },
  48220. enumerable: true,
  48221. configurable: true
  48222. });
  48223. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48224. /**
  48225. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48226. */
  48227. get: function () {
  48228. return this._speedRatio;
  48229. },
  48230. set: function (value) {
  48231. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48232. var animation = this._runtimeAnimations[index];
  48233. animation._prepareForSpeedRatioChange(value);
  48234. }
  48235. this._speedRatio = value;
  48236. },
  48237. enumerable: true,
  48238. configurable: true
  48239. });
  48240. // Methods
  48241. /**
  48242. * Synchronize and normalize current Animatable with a source Animatable.
  48243. * This is useful when using animation weights and when animations are not of the same length
  48244. * @param root defines the root Animatable to synchronize with
  48245. * @returns the current Animatable
  48246. */
  48247. Animatable.prototype.syncWith = function (root) {
  48248. this._syncRoot = root;
  48249. if (root) {
  48250. // Make sure this animatable will animate after the root
  48251. var index = this._scene._activeAnimatables.indexOf(this);
  48252. if (index > -1) {
  48253. this._scene._activeAnimatables.splice(index, 1);
  48254. this._scene._activeAnimatables.push(this);
  48255. }
  48256. }
  48257. return this;
  48258. };
  48259. Animatable.prototype.getAnimations = function () {
  48260. return this._runtimeAnimations;
  48261. };
  48262. Animatable.prototype.appendAnimations = function (target, animations) {
  48263. for (var index = 0; index < animations.length; index++) {
  48264. var animation = animations[index];
  48265. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  48266. }
  48267. };
  48268. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48269. var runtimeAnimations = this._runtimeAnimations;
  48270. for (var index = 0; index < runtimeAnimations.length; index++) {
  48271. if (runtimeAnimations[index].animation.targetProperty === property) {
  48272. return runtimeAnimations[index].animation;
  48273. }
  48274. }
  48275. return null;
  48276. };
  48277. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48278. var runtimeAnimations = this._runtimeAnimations;
  48279. for (var index = 0; index < runtimeAnimations.length; index++) {
  48280. if (runtimeAnimations[index].animation.targetProperty === property) {
  48281. return runtimeAnimations[index];
  48282. }
  48283. }
  48284. return null;
  48285. };
  48286. Animatable.prototype.reset = function () {
  48287. var runtimeAnimations = this._runtimeAnimations;
  48288. for (var index = 0; index < runtimeAnimations.length; index++) {
  48289. runtimeAnimations[index].reset();
  48290. }
  48291. // Reset to original value
  48292. for (index = 0; index < runtimeAnimations.length; index++) {
  48293. var animation = runtimeAnimations[index];
  48294. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48295. }
  48296. this._localDelayOffset = null;
  48297. this._pausedDelay = null;
  48298. };
  48299. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48300. var runtimeAnimations = this._runtimeAnimations;
  48301. for (var index = 0; index < runtimeAnimations.length; index++) {
  48302. runtimeAnimations[index].animation.enableBlending = true;
  48303. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48304. }
  48305. };
  48306. Animatable.prototype.disableBlending = function () {
  48307. var runtimeAnimations = this._runtimeAnimations;
  48308. for (var index = 0; index < runtimeAnimations.length; index++) {
  48309. runtimeAnimations[index].animation.enableBlending = false;
  48310. }
  48311. };
  48312. Animatable.prototype.goToFrame = function (frame) {
  48313. var runtimeAnimations = this._runtimeAnimations;
  48314. if (runtimeAnimations[0]) {
  48315. var fps = runtimeAnimations[0].animation.framePerSecond;
  48316. var currentFrame = runtimeAnimations[0].currentFrame;
  48317. var adjustTime = frame - currentFrame;
  48318. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48319. if (this._localDelayOffset === null) {
  48320. this._localDelayOffset = 0;
  48321. }
  48322. this._localDelayOffset -= delay;
  48323. }
  48324. for (var index = 0; index < runtimeAnimations.length; index++) {
  48325. runtimeAnimations[index].goToFrame(frame);
  48326. }
  48327. };
  48328. Animatable.prototype.pause = function () {
  48329. if (this._paused) {
  48330. return;
  48331. }
  48332. this._paused = true;
  48333. };
  48334. Animatable.prototype.restart = function () {
  48335. this._paused = false;
  48336. };
  48337. Animatable.prototype.stop = function (animationName) {
  48338. if (animationName) {
  48339. var idx = this._scene._activeAnimatables.indexOf(this);
  48340. if (idx > -1) {
  48341. var runtimeAnimations = this._runtimeAnimations;
  48342. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48343. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48344. continue;
  48345. }
  48346. runtimeAnimations[index].dispose();
  48347. runtimeAnimations.splice(index, 1);
  48348. }
  48349. if (runtimeAnimations.length == 0) {
  48350. this._scene._activeAnimatables.splice(idx, 1);
  48351. if (this.onAnimationEnd) {
  48352. this.onAnimationEnd();
  48353. }
  48354. }
  48355. }
  48356. }
  48357. else {
  48358. var index = this._scene._activeAnimatables.indexOf(this);
  48359. if (index > -1) {
  48360. this._scene._activeAnimatables.splice(index, 1);
  48361. var runtimeAnimations = this._runtimeAnimations;
  48362. for (var index = 0; index < runtimeAnimations.length; index++) {
  48363. runtimeAnimations[index].dispose();
  48364. }
  48365. if (this.onAnimationEnd) {
  48366. this.onAnimationEnd();
  48367. }
  48368. }
  48369. }
  48370. };
  48371. Animatable.prototype._animate = function (delay) {
  48372. if (this._paused) {
  48373. this.animationStarted = false;
  48374. if (this._pausedDelay === null) {
  48375. this._pausedDelay = delay;
  48376. }
  48377. return true;
  48378. }
  48379. if (this._localDelayOffset === null) {
  48380. this._localDelayOffset = delay;
  48381. this._pausedDelay = null;
  48382. }
  48383. else if (this._pausedDelay !== null) {
  48384. this._localDelayOffset += delay - this._pausedDelay;
  48385. this._pausedDelay = null;
  48386. }
  48387. if (this._weight === 0) {
  48388. return true;
  48389. }
  48390. // Animating
  48391. var running = false;
  48392. var runtimeAnimations = this._runtimeAnimations;
  48393. var index;
  48394. for (index = 0; index < runtimeAnimations.length; index++) {
  48395. var animation = runtimeAnimations[index];
  48396. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48397. running = running || isRunning;
  48398. }
  48399. this.animationStarted = running;
  48400. if (!running) {
  48401. // Remove from active animatables
  48402. index = this._scene._activeAnimatables.indexOf(this);
  48403. this._scene._activeAnimatables.splice(index, 1);
  48404. // Dispose all runtime animations
  48405. for (index = 0; index < runtimeAnimations.length; index++) {
  48406. runtimeAnimations[index].dispose();
  48407. }
  48408. }
  48409. if (!running && this.onAnimationEnd) {
  48410. this.onAnimationEnd();
  48411. this.onAnimationEnd = null;
  48412. }
  48413. return running;
  48414. };
  48415. return Animatable;
  48416. }());
  48417. BABYLON.Animatable = Animatable;
  48418. })(BABYLON || (BABYLON = {}));
  48419. //# sourceMappingURL=babylon.animatable.js.map
  48420. "use strict";
  48421. var BABYLON;
  48422. (function (BABYLON) {
  48423. var EasingFunction = /** @class */ (function () {
  48424. function EasingFunction() {
  48425. // Properties
  48426. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48427. }
  48428. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48429. get: function () {
  48430. return EasingFunction._EASINGMODE_EASEIN;
  48431. },
  48432. enumerable: true,
  48433. configurable: true
  48434. });
  48435. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48436. get: function () {
  48437. return EasingFunction._EASINGMODE_EASEOUT;
  48438. },
  48439. enumerable: true,
  48440. configurable: true
  48441. });
  48442. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48443. get: function () {
  48444. return EasingFunction._EASINGMODE_EASEINOUT;
  48445. },
  48446. enumerable: true,
  48447. configurable: true
  48448. });
  48449. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48450. var n = Math.min(Math.max(easingMode, 0), 2);
  48451. this._easingMode = n;
  48452. };
  48453. EasingFunction.prototype.getEasingMode = function () {
  48454. return this._easingMode;
  48455. };
  48456. EasingFunction.prototype.easeInCore = function (gradient) {
  48457. throw new Error('You must implement this method');
  48458. };
  48459. EasingFunction.prototype.ease = function (gradient) {
  48460. switch (this._easingMode) {
  48461. case EasingFunction.EASINGMODE_EASEIN:
  48462. return this.easeInCore(gradient);
  48463. case EasingFunction.EASINGMODE_EASEOUT:
  48464. return (1 - this.easeInCore(1 - gradient));
  48465. }
  48466. if (gradient >= 0.5) {
  48467. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48468. }
  48469. return (this.easeInCore(gradient * 2) * 0.5);
  48470. };
  48471. //Statics
  48472. EasingFunction._EASINGMODE_EASEIN = 0;
  48473. EasingFunction._EASINGMODE_EASEOUT = 1;
  48474. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48475. return EasingFunction;
  48476. }());
  48477. BABYLON.EasingFunction = EasingFunction;
  48478. var CircleEase = /** @class */ (function (_super) {
  48479. __extends(CircleEase, _super);
  48480. function CircleEase() {
  48481. return _super !== null && _super.apply(this, arguments) || this;
  48482. }
  48483. CircleEase.prototype.easeInCore = function (gradient) {
  48484. gradient = Math.max(0, Math.min(1, gradient));
  48485. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48486. };
  48487. return CircleEase;
  48488. }(EasingFunction));
  48489. BABYLON.CircleEase = CircleEase;
  48490. var BackEase = /** @class */ (function (_super) {
  48491. __extends(BackEase, _super);
  48492. function BackEase(amplitude) {
  48493. if (amplitude === void 0) { amplitude = 1; }
  48494. var _this = _super.call(this) || this;
  48495. _this.amplitude = amplitude;
  48496. return _this;
  48497. }
  48498. BackEase.prototype.easeInCore = function (gradient) {
  48499. var num = Math.max(0, this.amplitude);
  48500. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48501. };
  48502. return BackEase;
  48503. }(EasingFunction));
  48504. BABYLON.BackEase = BackEase;
  48505. var BounceEase = /** @class */ (function (_super) {
  48506. __extends(BounceEase, _super);
  48507. function BounceEase(bounces, bounciness) {
  48508. if (bounces === void 0) { bounces = 3; }
  48509. if (bounciness === void 0) { bounciness = 2; }
  48510. var _this = _super.call(this) || this;
  48511. _this.bounces = bounces;
  48512. _this.bounciness = bounciness;
  48513. return _this;
  48514. }
  48515. BounceEase.prototype.easeInCore = function (gradient) {
  48516. var y = Math.max(0.0, this.bounces);
  48517. var bounciness = this.bounciness;
  48518. if (bounciness <= 1.0) {
  48519. bounciness = 1.001;
  48520. }
  48521. var num9 = Math.pow(bounciness, y);
  48522. var num5 = 1.0 - bounciness;
  48523. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48524. var num15 = gradient * num4;
  48525. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48526. var num3 = Math.floor(num65);
  48527. var num13 = num3 + 1.0;
  48528. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48529. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48530. var num7 = (num8 + num12) * 0.5;
  48531. var num6 = gradient - num7;
  48532. var num2 = num7 - num8;
  48533. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48534. };
  48535. return BounceEase;
  48536. }(EasingFunction));
  48537. BABYLON.BounceEase = BounceEase;
  48538. var CubicEase = /** @class */ (function (_super) {
  48539. __extends(CubicEase, _super);
  48540. function CubicEase() {
  48541. return _super !== null && _super.apply(this, arguments) || this;
  48542. }
  48543. CubicEase.prototype.easeInCore = function (gradient) {
  48544. return (gradient * gradient * gradient);
  48545. };
  48546. return CubicEase;
  48547. }(EasingFunction));
  48548. BABYLON.CubicEase = CubicEase;
  48549. var ElasticEase = /** @class */ (function (_super) {
  48550. __extends(ElasticEase, _super);
  48551. function ElasticEase(oscillations, springiness) {
  48552. if (oscillations === void 0) { oscillations = 3; }
  48553. if (springiness === void 0) { springiness = 3; }
  48554. var _this = _super.call(this) || this;
  48555. _this.oscillations = oscillations;
  48556. _this.springiness = springiness;
  48557. return _this;
  48558. }
  48559. ElasticEase.prototype.easeInCore = function (gradient) {
  48560. var num2;
  48561. var num3 = Math.max(0.0, this.oscillations);
  48562. var num = Math.max(0.0, this.springiness);
  48563. if (num == 0) {
  48564. num2 = gradient;
  48565. }
  48566. else {
  48567. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48568. }
  48569. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48570. };
  48571. return ElasticEase;
  48572. }(EasingFunction));
  48573. BABYLON.ElasticEase = ElasticEase;
  48574. var ExponentialEase = /** @class */ (function (_super) {
  48575. __extends(ExponentialEase, _super);
  48576. function ExponentialEase(exponent) {
  48577. if (exponent === void 0) { exponent = 2; }
  48578. var _this = _super.call(this) || this;
  48579. _this.exponent = exponent;
  48580. return _this;
  48581. }
  48582. ExponentialEase.prototype.easeInCore = function (gradient) {
  48583. if (this.exponent <= 0) {
  48584. return gradient;
  48585. }
  48586. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48587. };
  48588. return ExponentialEase;
  48589. }(EasingFunction));
  48590. BABYLON.ExponentialEase = ExponentialEase;
  48591. var PowerEase = /** @class */ (function (_super) {
  48592. __extends(PowerEase, _super);
  48593. function PowerEase(power) {
  48594. if (power === void 0) { power = 2; }
  48595. var _this = _super.call(this) || this;
  48596. _this.power = power;
  48597. return _this;
  48598. }
  48599. PowerEase.prototype.easeInCore = function (gradient) {
  48600. var y = Math.max(0.0, this.power);
  48601. return Math.pow(gradient, y);
  48602. };
  48603. return PowerEase;
  48604. }(EasingFunction));
  48605. BABYLON.PowerEase = PowerEase;
  48606. var QuadraticEase = /** @class */ (function (_super) {
  48607. __extends(QuadraticEase, _super);
  48608. function QuadraticEase() {
  48609. return _super !== null && _super.apply(this, arguments) || this;
  48610. }
  48611. QuadraticEase.prototype.easeInCore = function (gradient) {
  48612. return (gradient * gradient);
  48613. };
  48614. return QuadraticEase;
  48615. }(EasingFunction));
  48616. BABYLON.QuadraticEase = QuadraticEase;
  48617. var QuarticEase = /** @class */ (function (_super) {
  48618. __extends(QuarticEase, _super);
  48619. function QuarticEase() {
  48620. return _super !== null && _super.apply(this, arguments) || this;
  48621. }
  48622. QuarticEase.prototype.easeInCore = function (gradient) {
  48623. return (gradient * gradient * gradient * gradient);
  48624. };
  48625. return QuarticEase;
  48626. }(EasingFunction));
  48627. BABYLON.QuarticEase = QuarticEase;
  48628. var QuinticEase = /** @class */ (function (_super) {
  48629. __extends(QuinticEase, _super);
  48630. function QuinticEase() {
  48631. return _super !== null && _super.apply(this, arguments) || this;
  48632. }
  48633. QuinticEase.prototype.easeInCore = function (gradient) {
  48634. return (gradient * gradient * gradient * gradient * gradient);
  48635. };
  48636. return QuinticEase;
  48637. }(EasingFunction));
  48638. BABYLON.QuinticEase = QuinticEase;
  48639. var SineEase = /** @class */ (function (_super) {
  48640. __extends(SineEase, _super);
  48641. function SineEase() {
  48642. return _super !== null && _super.apply(this, arguments) || this;
  48643. }
  48644. SineEase.prototype.easeInCore = function (gradient) {
  48645. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48646. };
  48647. return SineEase;
  48648. }(EasingFunction));
  48649. BABYLON.SineEase = SineEase;
  48650. var BezierCurveEase = /** @class */ (function (_super) {
  48651. __extends(BezierCurveEase, _super);
  48652. function BezierCurveEase(x1, y1, x2, y2) {
  48653. if (x1 === void 0) { x1 = 0; }
  48654. if (y1 === void 0) { y1 = 0; }
  48655. if (x2 === void 0) { x2 = 1; }
  48656. if (y2 === void 0) { y2 = 1; }
  48657. var _this = _super.call(this) || this;
  48658. _this.x1 = x1;
  48659. _this.y1 = y1;
  48660. _this.x2 = x2;
  48661. _this.y2 = y2;
  48662. return _this;
  48663. }
  48664. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48665. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48666. };
  48667. return BezierCurveEase;
  48668. }(EasingFunction));
  48669. BABYLON.BezierCurveEase = BezierCurveEase;
  48670. })(BABYLON || (BABYLON = {}));
  48671. //# sourceMappingURL=babylon.easing.js.map
  48672. "use strict";
  48673. var BABYLON;
  48674. (function (BABYLON) {
  48675. /**
  48676. * A Condition applied to an Action
  48677. */
  48678. var Condition = /** @class */ (function () {
  48679. /**
  48680. * Creates a new Condition
  48681. * @param actionManager the manager of the action the condition is applied to
  48682. */
  48683. function Condition(actionManager) {
  48684. this._actionManager = actionManager;
  48685. }
  48686. /**
  48687. * Check if the current condition is valid
  48688. * @returns a boolean
  48689. */
  48690. Condition.prototype.isValid = function () {
  48691. return true;
  48692. };
  48693. /**
  48694. * Internal only
  48695. * @ignore
  48696. */
  48697. Condition.prototype._getProperty = function (propertyPath) {
  48698. return this._actionManager._getProperty(propertyPath);
  48699. };
  48700. /**
  48701. * Internal only
  48702. * @ignore
  48703. */
  48704. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48705. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48706. };
  48707. /**
  48708. * Serialize placeholder for child classes
  48709. * @returns the serialized object
  48710. */
  48711. Condition.prototype.serialize = function () {
  48712. };
  48713. /**
  48714. * Internal only
  48715. * @ignore
  48716. */
  48717. Condition.prototype._serialize = function (serializedCondition) {
  48718. return {
  48719. type: 2,
  48720. children: [],
  48721. name: serializedCondition.name,
  48722. properties: serializedCondition.properties
  48723. };
  48724. };
  48725. return Condition;
  48726. }());
  48727. BABYLON.Condition = Condition;
  48728. /**
  48729. * Defines specific conditional operators as extensions of Condition
  48730. */
  48731. var ValueCondition = /** @class */ (function (_super) {
  48732. __extends(ValueCondition, _super);
  48733. /**
  48734. * Creates a new ValueCondition
  48735. * @param actionManager manager for the action the condition applies to
  48736. * @param target for the action
  48737. * @param propertyPath path to specify the property of the target the conditional operator uses
  48738. * @param value the vale compared by the conditional operator against the current value of the property
  48739. * @param operator the conditional operator, default {BABYLON.ValueCondition.IsEqual}
  48740. */
  48741. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48742. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48743. var _this = _super.call(this, actionManager) || this;
  48744. _this.propertyPath = propertyPath;
  48745. _this.value = value;
  48746. _this.operator = operator;
  48747. _this._target = target;
  48748. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48749. _this._property = _this._getProperty(_this.propertyPath);
  48750. return _this;
  48751. }
  48752. Object.defineProperty(ValueCondition, "IsEqual", {
  48753. /**
  48754. * returns the number for IsEqual
  48755. */
  48756. get: function () {
  48757. return ValueCondition._IsEqual;
  48758. },
  48759. enumerable: true,
  48760. configurable: true
  48761. });
  48762. Object.defineProperty(ValueCondition, "IsDifferent", {
  48763. /**
  48764. * Returns the number for IsDifferent
  48765. */
  48766. get: function () {
  48767. return ValueCondition._IsDifferent;
  48768. },
  48769. enumerable: true,
  48770. configurable: true
  48771. });
  48772. Object.defineProperty(ValueCondition, "IsGreater", {
  48773. /**
  48774. * Returns the number for IsGreater
  48775. */
  48776. get: function () {
  48777. return ValueCondition._IsGreater;
  48778. },
  48779. enumerable: true,
  48780. configurable: true
  48781. });
  48782. Object.defineProperty(ValueCondition, "IsLesser", {
  48783. /**
  48784. * Returns the number for IsLesser
  48785. */
  48786. get: function () {
  48787. return ValueCondition._IsLesser;
  48788. },
  48789. enumerable: true,
  48790. configurable: true
  48791. });
  48792. /**
  48793. * Compares the given value with the property value for the specified conditional operator
  48794. * @returns the result of the comparison
  48795. */
  48796. ValueCondition.prototype.isValid = function () {
  48797. switch (this.operator) {
  48798. case ValueCondition.IsGreater:
  48799. return this._effectiveTarget[this._property] > this.value;
  48800. case ValueCondition.IsLesser:
  48801. return this._effectiveTarget[this._property] < this.value;
  48802. case ValueCondition.IsEqual:
  48803. case ValueCondition.IsDifferent:
  48804. var check;
  48805. if (this.value.equals) {
  48806. check = this.value.equals(this._effectiveTarget[this._property]);
  48807. }
  48808. else {
  48809. check = this.value === this._effectiveTarget[this._property];
  48810. }
  48811. return this.operator === ValueCondition.IsEqual ? check : !check;
  48812. }
  48813. return false;
  48814. };
  48815. /**
  48816. * Serialize the ValueCondition into a JSON compatible object
  48817. * @returns serialization object
  48818. */
  48819. ValueCondition.prototype.serialize = function () {
  48820. return this._serialize({
  48821. name: "ValueCondition",
  48822. properties: [
  48823. BABYLON.Action._GetTargetProperty(this._target),
  48824. { name: "propertyPath", value: this.propertyPath },
  48825. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48826. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48827. ]
  48828. });
  48829. };
  48830. /**
  48831. * Gets the name of the conditional operator for the ValueCondition
  48832. * @param operator the conditional operator
  48833. * @returns the name
  48834. */
  48835. ValueCondition.GetOperatorName = function (operator) {
  48836. switch (operator) {
  48837. case ValueCondition._IsEqual: return "IsEqual";
  48838. case ValueCondition._IsDifferent: return "IsDifferent";
  48839. case ValueCondition._IsGreater: return "IsGreater";
  48840. case ValueCondition._IsLesser: return "IsLesser";
  48841. default: return "";
  48842. }
  48843. };
  48844. /**
  48845. * Internal only
  48846. * @ignore
  48847. */
  48848. ValueCondition._IsEqual = 0;
  48849. /**
  48850. * Internal only
  48851. * @ignore
  48852. */
  48853. ValueCondition._IsDifferent = 1;
  48854. /**
  48855. * Internal only
  48856. * @ignore
  48857. */
  48858. ValueCondition._IsGreater = 2;
  48859. /**
  48860. * Internal only
  48861. * @ignore
  48862. */
  48863. ValueCondition._IsLesser = 3;
  48864. return ValueCondition;
  48865. }(Condition));
  48866. BABYLON.ValueCondition = ValueCondition;
  48867. /**
  48868. * Defines a predicate condition as an extension of Condition
  48869. */
  48870. var PredicateCondition = /** @class */ (function (_super) {
  48871. __extends(PredicateCondition, _super);
  48872. /**
  48873. * Creates a new {BABYLON.PredicateCondition}
  48874. * @param actionManager manager for the action the condition applies to
  48875. * @param predicate
  48876. */
  48877. function PredicateCondition(actionManager, predicate) {
  48878. var _this = _super.call(this, actionManager) || this;
  48879. _this.predicate = predicate;
  48880. return _this;
  48881. }
  48882. /**
  48883. * @returns the validity of the predicate condition
  48884. */
  48885. PredicateCondition.prototype.isValid = function () {
  48886. return this.predicate();
  48887. };
  48888. return PredicateCondition;
  48889. }(Condition));
  48890. BABYLON.PredicateCondition = PredicateCondition;
  48891. /**
  48892. * Defines a state condition as an extension of {BABYLON.Condition}
  48893. */
  48894. var StateCondition = /** @class */ (function (_super) {
  48895. __extends(StateCondition, _super);
  48896. /**
  48897. * Creates a new {BABYLON.StateCondition}
  48898. * @param actionManager manager for the action the condition applies to
  48899. * @param target of the condition
  48900. * @param value to compare with target state
  48901. */
  48902. function StateCondition(actionManager, target, value) {
  48903. var _this = _super.call(this, actionManager) || this;
  48904. _this.value = value;
  48905. _this._target = target;
  48906. return _this;
  48907. }
  48908. /**
  48909. * @returns the validity of the state
  48910. */
  48911. StateCondition.prototype.isValid = function () {
  48912. return this._target.state === this.value;
  48913. };
  48914. /**
  48915. * Serialize the {BABYLON.StateCondition} into a JSON compatible object
  48916. * @returns serialization object
  48917. */
  48918. StateCondition.prototype.serialize = function () {
  48919. return this._serialize({
  48920. name: "StateCondition",
  48921. properties: [
  48922. BABYLON.Action._GetTargetProperty(this._target),
  48923. { name: "value", value: this.value }
  48924. ]
  48925. });
  48926. };
  48927. return StateCondition;
  48928. }(Condition));
  48929. BABYLON.StateCondition = StateCondition;
  48930. })(BABYLON || (BABYLON = {}));
  48931. //# sourceMappingURL=babylon.condition.js.map
  48932. "use strict";
  48933. var BABYLON;
  48934. (function (BABYLON) {
  48935. /**
  48936. * The action to be carried out following a trigger
  48937. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  48938. */
  48939. var Action = /** @class */ (function () {
  48940. /**
  48941. * Creates a new Action
  48942. * @param triggerOptions the trigger, with or without parameters, for the action
  48943. * @param condition an optional determinant of action
  48944. */
  48945. function Action(triggerOptions, condition) {
  48946. this.triggerOptions = triggerOptions;
  48947. /**
  48948. * An event triggered prior to action being executed.
  48949. * @type Observable
  48950. */
  48951. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48952. if (triggerOptions.parameter) {
  48953. this.trigger = triggerOptions.trigger;
  48954. this._triggerParameter = triggerOptions.parameter;
  48955. }
  48956. else {
  48957. this.trigger = triggerOptions;
  48958. }
  48959. this._nextActiveAction = this;
  48960. this._condition = condition;
  48961. }
  48962. /**
  48963. * Internal only
  48964. * @ignore
  48965. */
  48966. Action.prototype._prepare = function () {
  48967. };
  48968. /**
  48969. * Gets the trigger parameters
  48970. * @returns the trigger parameters
  48971. */
  48972. Action.prototype.getTriggerParameter = function () {
  48973. return this._triggerParameter;
  48974. };
  48975. /**
  48976. * Internal only - executes current action event
  48977. * @ignore
  48978. */
  48979. Action.prototype._executeCurrent = function (evt) {
  48980. if (this._nextActiveAction._condition) {
  48981. var condition = this._nextActiveAction._condition;
  48982. var currentRenderId = this._actionManager.getScene().getRenderId();
  48983. // We cache the current evaluation for the current frame
  48984. if (condition._evaluationId === currentRenderId) {
  48985. if (!condition._currentResult) {
  48986. return;
  48987. }
  48988. }
  48989. else {
  48990. condition._evaluationId = currentRenderId;
  48991. if (!condition.isValid()) {
  48992. condition._currentResult = false;
  48993. return;
  48994. }
  48995. condition._currentResult = true;
  48996. }
  48997. }
  48998. this.onBeforeExecuteObservable.notifyObservers(this);
  48999. this._nextActiveAction.execute(evt);
  49000. this.skipToNextActiveAction();
  49001. };
  49002. /**
  49003. * Execute placeholder for child classes
  49004. * @param evt optional action event
  49005. */
  49006. Action.prototype.execute = function (evt) {
  49007. };
  49008. /**
  49009. * Skips to next active action
  49010. */
  49011. Action.prototype.skipToNextActiveAction = function () {
  49012. if (this._nextActiveAction._child) {
  49013. if (!this._nextActiveAction._child._actionManager) {
  49014. this._nextActiveAction._child._actionManager = this._actionManager;
  49015. }
  49016. this._nextActiveAction = this._nextActiveAction._child;
  49017. }
  49018. else {
  49019. this._nextActiveAction = this;
  49020. }
  49021. };
  49022. /**
  49023. * Adds action to chain of actions, may be a DoNothingAction
  49024. * @param index The index of the attribute.
  49025. * @returns The action passed in
  49026. * @see https://www.babylonjs-playground.com/#1T30HR#0
  49027. */
  49028. Action.prototype.then = function (action) {
  49029. this._child = action;
  49030. action._actionManager = this._actionManager;
  49031. action._prepare();
  49032. return action;
  49033. };
  49034. /**
  49035. * Internal only
  49036. * @ignore
  49037. */
  49038. Action.prototype._getProperty = function (propertyPath) {
  49039. return this._actionManager._getProperty(propertyPath);
  49040. };
  49041. /**
  49042. * Internal only
  49043. * @ignore
  49044. */
  49045. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  49046. return this._actionManager._getEffectiveTarget(target, propertyPath);
  49047. };
  49048. /**
  49049. * Serialize placeholder for child classes
  49050. * @param parent of child
  49051. * @returns the serialized object
  49052. */
  49053. Action.prototype.serialize = function (parent) {
  49054. };
  49055. /**
  49056. * Internal only called by serialize
  49057. * @ignore
  49058. */
  49059. Action.prototype._serialize = function (serializedAction, parent) {
  49060. var serializationObject = {
  49061. type: 1,
  49062. children: [],
  49063. name: serializedAction.name,
  49064. properties: serializedAction.properties || []
  49065. };
  49066. // Serialize child
  49067. if (this._child) {
  49068. this._child.serialize(serializationObject);
  49069. }
  49070. // Check if "this" has a condition
  49071. if (this._condition) {
  49072. var serializedCondition = this._condition.serialize();
  49073. serializedCondition.children.push(serializationObject);
  49074. if (parent) {
  49075. parent.children.push(serializedCondition);
  49076. }
  49077. return serializedCondition;
  49078. }
  49079. if (parent) {
  49080. parent.children.push(serializationObject);
  49081. }
  49082. return serializationObject;
  49083. };
  49084. /**
  49085. * Internal only
  49086. * @ignore
  49087. */
  49088. Action._SerializeValueAsString = function (value) {
  49089. if (typeof value === "number") {
  49090. return value.toString();
  49091. }
  49092. if (typeof value === "boolean") {
  49093. return value ? "true" : "false";
  49094. }
  49095. if (value instanceof BABYLON.Vector2) {
  49096. return value.x + ", " + value.y;
  49097. }
  49098. if (value instanceof BABYLON.Vector3) {
  49099. return value.x + ", " + value.y + ", " + value.z;
  49100. }
  49101. if (value instanceof BABYLON.Color3) {
  49102. return value.r + ", " + value.g + ", " + value.b;
  49103. }
  49104. if (value instanceof BABYLON.Color4) {
  49105. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  49106. }
  49107. return value; // string
  49108. };
  49109. /**
  49110. * Internal only
  49111. * @ignore
  49112. */
  49113. Action._GetTargetProperty = function (target) {
  49114. return {
  49115. name: "target",
  49116. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  49117. : target instanceof BABYLON.Light ? "LightProperties"
  49118. : target instanceof BABYLON.Camera ? "CameraProperties"
  49119. : "SceneProperties",
  49120. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  49121. };
  49122. };
  49123. return Action;
  49124. }());
  49125. BABYLON.Action = Action;
  49126. })(BABYLON || (BABYLON = {}));
  49127. //# sourceMappingURL=babylon.action.js.map
  49128. "use strict";
  49129. var BABYLON;
  49130. (function (BABYLON) {
  49131. /**
  49132. * ActionEvent is the event being sent when an action is triggered.
  49133. */
  49134. var ActionEvent = /** @class */ (function () {
  49135. /**
  49136. * @param source The mesh or sprite that triggered the action.
  49137. * @param pointerX The X mouse cursor position at the time of the event
  49138. * @param pointerY The Y mouse cursor position at the time of the event
  49139. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  49140. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  49141. */
  49142. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  49143. this.source = source;
  49144. this.pointerX = pointerX;
  49145. this.pointerY = pointerY;
  49146. this.meshUnderPointer = meshUnderPointer;
  49147. this.sourceEvent = sourceEvent;
  49148. this.additionalData = additionalData;
  49149. }
  49150. /**
  49151. * Helper function to auto-create an ActionEvent from a source mesh.
  49152. * @param source The source mesh that triggered the event
  49153. * @param evt {Event} The original (browser) event
  49154. */
  49155. ActionEvent.CreateNew = function (source, evt, additionalData) {
  49156. var scene = source.getScene();
  49157. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49158. };
  49159. /**
  49160. * Helper function to auto-create an ActionEvent from a source mesh.
  49161. * @param source The source sprite that triggered the event
  49162. * @param scene Scene associated with the sprite
  49163. * @param evt {Event} The original (browser) event
  49164. */
  49165. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  49166. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  49167. };
  49168. /**
  49169. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  49170. * @param scene the scene where the event occurred
  49171. * @param evt {Event} The original (browser) event
  49172. */
  49173. ActionEvent.CreateNewFromScene = function (scene, evt) {
  49174. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  49175. };
  49176. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  49177. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  49178. };
  49179. return ActionEvent;
  49180. }());
  49181. BABYLON.ActionEvent = ActionEvent;
  49182. /**
  49183. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  49184. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  49185. */
  49186. var ActionManager = /** @class */ (function () {
  49187. function ActionManager(scene) {
  49188. // Members
  49189. this.actions = new Array();
  49190. this.hoverCursor = '';
  49191. this._scene = scene;
  49192. scene._actionManagers.push(this);
  49193. }
  49194. Object.defineProperty(ActionManager, "NothingTrigger", {
  49195. get: function () {
  49196. return ActionManager._NothingTrigger;
  49197. },
  49198. enumerable: true,
  49199. configurable: true
  49200. });
  49201. Object.defineProperty(ActionManager, "OnPickTrigger", {
  49202. get: function () {
  49203. return ActionManager._OnPickTrigger;
  49204. },
  49205. enumerable: true,
  49206. configurable: true
  49207. });
  49208. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  49209. get: function () {
  49210. return ActionManager._OnLeftPickTrigger;
  49211. },
  49212. enumerable: true,
  49213. configurable: true
  49214. });
  49215. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  49216. get: function () {
  49217. return ActionManager._OnRightPickTrigger;
  49218. },
  49219. enumerable: true,
  49220. configurable: true
  49221. });
  49222. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49223. get: function () {
  49224. return ActionManager._OnCenterPickTrigger;
  49225. },
  49226. enumerable: true,
  49227. configurable: true
  49228. });
  49229. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49230. get: function () {
  49231. return ActionManager._OnPickDownTrigger;
  49232. },
  49233. enumerable: true,
  49234. configurable: true
  49235. });
  49236. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49237. get: function () {
  49238. return ActionManager._OnDoublePickTrigger;
  49239. },
  49240. enumerable: true,
  49241. configurable: true
  49242. });
  49243. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49244. get: function () {
  49245. return ActionManager._OnPickUpTrigger;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49251. /// This trigger will only be raised if you also declared a OnPickDown
  49252. get: function () {
  49253. return ActionManager._OnPickOutTrigger;
  49254. },
  49255. enumerable: true,
  49256. configurable: true
  49257. });
  49258. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49259. get: function () {
  49260. return ActionManager._OnLongPressTrigger;
  49261. },
  49262. enumerable: true,
  49263. configurable: true
  49264. });
  49265. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49266. get: function () {
  49267. return ActionManager._OnPointerOverTrigger;
  49268. },
  49269. enumerable: true,
  49270. configurable: true
  49271. });
  49272. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49273. get: function () {
  49274. return ActionManager._OnPointerOutTrigger;
  49275. },
  49276. enumerable: true,
  49277. configurable: true
  49278. });
  49279. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49280. get: function () {
  49281. return ActionManager._OnEveryFrameTrigger;
  49282. },
  49283. enumerable: true,
  49284. configurable: true
  49285. });
  49286. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49287. get: function () {
  49288. return ActionManager._OnIntersectionEnterTrigger;
  49289. },
  49290. enumerable: true,
  49291. configurable: true
  49292. });
  49293. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49294. get: function () {
  49295. return ActionManager._OnIntersectionExitTrigger;
  49296. },
  49297. enumerable: true,
  49298. configurable: true
  49299. });
  49300. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49301. get: function () {
  49302. return ActionManager._OnKeyDownTrigger;
  49303. },
  49304. enumerable: true,
  49305. configurable: true
  49306. });
  49307. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49308. get: function () {
  49309. return ActionManager._OnKeyUpTrigger;
  49310. },
  49311. enumerable: true,
  49312. configurable: true
  49313. });
  49314. // Methods
  49315. ActionManager.prototype.dispose = function () {
  49316. var index = this._scene._actionManagers.indexOf(this);
  49317. for (var i = 0; i < this.actions.length; i++) {
  49318. var action = this.actions[i];
  49319. ActionManager.Triggers[action.trigger]--;
  49320. if (ActionManager.Triggers[action.trigger] === 0) {
  49321. delete ActionManager.Triggers[action.trigger];
  49322. }
  49323. }
  49324. if (index > -1) {
  49325. this._scene._actionManagers.splice(index, 1);
  49326. }
  49327. };
  49328. ActionManager.prototype.getScene = function () {
  49329. return this._scene;
  49330. };
  49331. /**
  49332. * Does this action manager handles actions of any of the given triggers
  49333. * @param {number[]} triggers - the triggers to be tested
  49334. * @return {boolean} whether one (or more) of the triggers is handeled
  49335. */
  49336. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49337. for (var index = 0; index < this.actions.length; index++) {
  49338. var action = this.actions[index];
  49339. if (triggers.indexOf(action.trigger) > -1) {
  49340. return true;
  49341. }
  49342. }
  49343. return false;
  49344. };
  49345. /**
  49346. * Does this action manager handles actions of a given trigger
  49347. * @param {number} trigger - the trigger to be tested
  49348. * @return {boolean} whether the trigger is handeled
  49349. */
  49350. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49351. for (var index = 0; index < this.actions.length; index++) {
  49352. var action = this.actions[index];
  49353. if (action.trigger === trigger) {
  49354. return true;
  49355. }
  49356. }
  49357. return false;
  49358. };
  49359. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49360. /**
  49361. * Does this action manager has pointer triggers
  49362. * @return {boolean} whether or not it has pointer triggers
  49363. */
  49364. get: function () {
  49365. for (var index = 0; index < this.actions.length; index++) {
  49366. var action = this.actions[index];
  49367. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49368. return true;
  49369. }
  49370. }
  49371. return false;
  49372. },
  49373. enumerable: true,
  49374. configurable: true
  49375. });
  49376. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49377. /**
  49378. * Does this action manager has pick triggers
  49379. * @return {boolean} whether or not it has pick triggers
  49380. */
  49381. get: function () {
  49382. for (var index = 0; index < this.actions.length; index++) {
  49383. var action = this.actions[index];
  49384. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49385. return true;
  49386. }
  49387. }
  49388. return false;
  49389. },
  49390. enumerable: true,
  49391. configurable: true
  49392. });
  49393. Object.defineProperty(ActionManager, "HasTriggers", {
  49394. /**
  49395. * Does exist one action manager with at least one trigger
  49396. * @return {boolean} whether or not it exists one action manager with one trigger
  49397. **/
  49398. get: function () {
  49399. for (var t in ActionManager.Triggers) {
  49400. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49401. return true;
  49402. }
  49403. }
  49404. return false;
  49405. },
  49406. enumerable: true,
  49407. configurable: true
  49408. });
  49409. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49410. /**
  49411. * Does exist one action manager with at least one pick trigger
  49412. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49413. **/
  49414. get: function () {
  49415. for (var t in ActionManager.Triggers) {
  49416. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49417. var t_int = parseInt(t);
  49418. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49419. return true;
  49420. }
  49421. }
  49422. }
  49423. return false;
  49424. },
  49425. enumerable: true,
  49426. configurable: true
  49427. });
  49428. /**
  49429. * Does exist one action manager that handles actions of a given trigger
  49430. * @param {number} trigger - the trigger to be tested
  49431. * @return {boolean} whether the trigger is handeled by at least one action manager
  49432. **/
  49433. ActionManager.HasSpecificTrigger = function (trigger) {
  49434. for (var t in ActionManager.Triggers) {
  49435. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49436. var t_int = parseInt(t);
  49437. if (t_int === trigger) {
  49438. return true;
  49439. }
  49440. }
  49441. }
  49442. return false;
  49443. };
  49444. /**
  49445. * Registers an action to this action manager
  49446. * @param {BABYLON.Action} action - the action to be registered
  49447. * @return {BABYLON.Action} the action amended (prepared) after registration
  49448. */
  49449. ActionManager.prototype.registerAction = function (action) {
  49450. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49451. if (this.getScene().actionManager !== this) {
  49452. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49453. return null;
  49454. }
  49455. }
  49456. this.actions.push(action);
  49457. if (ActionManager.Triggers[action.trigger]) {
  49458. ActionManager.Triggers[action.trigger]++;
  49459. }
  49460. else {
  49461. ActionManager.Triggers[action.trigger] = 1;
  49462. }
  49463. action._actionManager = this;
  49464. action._prepare();
  49465. return action;
  49466. };
  49467. /**
  49468. * Unregisters an action to this action manager
  49469. * @param action The action to be unregistered
  49470. * @return whether the action has been unregistered
  49471. */
  49472. ActionManager.prototype.unregisterAction = function (action) {
  49473. var index = this.actions.indexOf(action);
  49474. if (index !== -1) {
  49475. this.actions.splice(index, 1);
  49476. ActionManager.Triggers[action.trigger] -= 1;
  49477. if (ActionManager.Triggers[action.trigger] === 0) {
  49478. delete ActionManager.Triggers[action.trigger];
  49479. }
  49480. delete action._actionManager;
  49481. return true;
  49482. }
  49483. return false;
  49484. };
  49485. /**
  49486. * Process a specific trigger
  49487. * @param {number} trigger - the trigger to process
  49488. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49489. */
  49490. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49491. for (var index = 0; index < this.actions.length; index++) {
  49492. var action = this.actions[index];
  49493. if (action.trigger === trigger) {
  49494. if (evt) {
  49495. if (trigger === ActionManager.OnKeyUpTrigger
  49496. || trigger === ActionManager.OnKeyDownTrigger) {
  49497. var parameter = action.getTriggerParameter();
  49498. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49499. if (!parameter.toLowerCase) {
  49500. continue;
  49501. }
  49502. var lowerCase = parameter.toLowerCase();
  49503. if (lowerCase !== evt.sourceEvent.key) {
  49504. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49505. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49506. if (actualkey !== lowerCase) {
  49507. continue;
  49508. }
  49509. }
  49510. }
  49511. }
  49512. }
  49513. action._executeCurrent(evt);
  49514. }
  49515. }
  49516. };
  49517. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49518. var properties = propertyPath.split(".");
  49519. for (var index = 0; index < properties.length - 1; index++) {
  49520. target = target[properties[index]];
  49521. }
  49522. return target;
  49523. };
  49524. ActionManager.prototype._getProperty = function (propertyPath) {
  49525. var properties = propertyPath.split(".");
  49526. return properties[properties.length - 1];
  49527. };
  49528. ActionManager.prototype.serialize = function (name) {
  49529. var root = {
  49530. children: new Array(),
  49531. name: name,
  49532. type: 3,
  49533. properties: new Array() // Empty for root but required
  49534. };
  49535. for (var i = 0; i < this.actions.length; i++) {
  49536. var triggerObject = {
  49537. type: 0,
  49538. children: new Array(),
  49539. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49540. properties: new Array()
  49541. };
  49542. var triggerOptions = this.actions[i].triggerOptions;
  49543. if (triggerOptions && typeof triggerOptions !== "number") {
  49544. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49545. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49546. }
  49547. else {
  49548. var parameter = {};
  49549. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49550. if (triggerOptions.parameter.mesh) {
  49551. parameter._meshId = triggerOptions.parameter.mesh.id;
  49552. }
  49553. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49554. }
  49555. }
  49556. // Serialize child action, recursively
  49557. this.actions[i].serialize(triggerObject);
  49558. // Add serialized trigger
  49559. root.children.push(triggerObject);
  49560. }
  49561. return root;
  49562. };
  49563. ActionManager.Parse = function (parsedActions, object, scene) {
  49564. var actionManager = new ActionManager(scene);
  49565. if (object === null)
  49566. scene.actionManager = actionManager;
  49567. else
  49568. object.actionManager = actionManager;
  49569. // instanciate a new object
  49570. var instanciate = function (name, params) {
  49571. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49572. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49573. newInstance.constructor.apply(newInstance, params);
  49574. return newInstance;
  49575. };
  49576. var parseParameter = function (name, value, target, propertyPath) {
  49577. if (propertyPath === null) {
  49578. // String, boolean or float
  49579. var floatValue = parseFloat(value);
  49580. if (value === "true" || value === "false")
  49581. return value === "true";
  49582. else
  49583. return isNaN(floatValue) ? value : floatValue;
  49584. }
  49585. var effectiveTarget = propertyPath.split(".");
  49586. var values = value.split(",");
  49587. // Get effective Target
  49588. for (var i = 0; i < effectiveTarget.length; i++) {
  49589. target = target[effectiveTarget[i]];
  49590. }
  49591. // Return appropriate value with its type
  49592. if (typeof (target) === "boolean")
  49593. return values[0] === "true";
  49594. if (typeof (target) === "string")
  49595. return values[0];
  49596. // Parameters with multiple values such as Vector3 etc.
  49597. var split = new Array();
  49598. for (var i = 0; i < values.length; i++)
  49599. split.push(parseFloat(values[i]));
  49600. if (target instanceof BABYLON.Vector3)
  49601. return BABYLON.Vector3.FromArray(split);
  49602. if (target instanceof BABYLON.Vector4)
  49603. return BABYLON.Vector4.FromArray(split);
  49604. if (target instanceof BABYLON.Color3)
  49605. return BABYLON.Color3.FromArray(split);
  49606. if (target instanceof BABYLON.Color4)
  49607. return BABYLON.Color4.FromArray(split);
  49608. return parseFloat(values[0]);
  49609. };
  49610. // traverse graph per trigger
  49611. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49612. if (combineArray === void 0) { combineArray = null; }
  49613. if (parsedAction.detached)
  49614. return;
  49615. var parameters = new Array();
  49616. var target = null;
  49617. var propertyPath = null;
  49618. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49619. // Parameters
  49620. if (parsedAction.type === 2)
  49621. parameters.push(actionManager);
  49622. else
  49623. parameters.push(trigger);
  49624. if (combine) {
  49625. var actions = new Array();
  49626. for (var j = 0; j < parsedAction.combine.length; j++) {
  49627. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49628. }
  49629. parameters.push(actions);
  49630. }
  49631. else {
  49632. for (var i = 0; i < parsedAction.properties.length; i++) {
  49633. var value = parsedAction.properties[i].value;
  49634. var name = parsedAction.properties[i].name;
  49635. var targetType = parsedAction.properties[i].targetType;
  49636. if (name === "target")
  49637. if (targetType !== null && targetType === "SceneProperties")
  49638. value = target = scene;
  49639. else
  49640. value = target = scene.getNodeByName(value);
  49641. else if (name === "parent")
  49642. value = scene.getNodeByName(value);
  49643. else if (name === "sound")
  49644. value = scene.getSoundByName(value);
  49645. else if (name !== "propertyPath") {
  49646. if (parsedAction.type === 2 && name === "operator")
  49647. value = BABYLON.ValueCondition[value];
  49648. else
  49649. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49650. }
  49651. else {
  49652. propertyPath = value;
  49653. }
  49654. parameters.push(value);
  49655. }
  49656. }
  49657. if (combineArray === null) {
  49658. parameters.push(condition);
  49659. }
  49660. else {
  49661. parameters.push(null);
  49662. }
  49663. // If interpolate value action
  49664. if (parsedAction.name === "InterpolateValueAction") {
  49665. var param = parameters[parameters.length - 2];
  49666. parameters[parameters.length - 1] = param;
  49667. parameters[parameters.length - 2] = condition;
  49668. }
  49669. // Action or condition(s) and not CombineAction
  49670. var newAction = instanciate(parsedAction.name, parameters);
  49671. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49672. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49673. if (action)
  49674. action.then(nothing);
  49675. else
  49676. actionManager.registerAction(nothing);
  49677. action = nothing;
  49678. }
  49679. if (combineArray === null) {
  49680. if (newAction instanceof BABYLON.Condition) {
  49681. condition = newAction;
  49682. newAction = action;
  49683. }
  49684. else {
  49685. condition = null;
  49686. if (action)
  49687. action.then(newAction);
  49688. else
  49689. actionManager.registerAction(newAction);
  49690. }
  49691. }
  49692. else {
  49693. combineArray.push(newAction);
  49694. }
  49695. for (var i = 0; i < parsedAction.children.length; i++)
  49696. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49697. };
  49698. // triggers
  49699. for (var i = 0; i < parsedActions.children.length; i++) {
  49700. var triggerParams;
  49701. var trigger = parsedActions.children[i];
  49702. if (trigger.properties.length > 0) {
  49703. var param = trigger.properties[0].value;
  49704. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49705. if (value._meshId) {
  49706. value.mesh = scene.getMeshByID(value._meshId);
  49707. }
  49708. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49709. }
  49710. else
  49711. triggerParams = ActionManager[trigger.name];
  49712. for (var j = 0; j < trigger.children.length; j++) {
  49713. if (!trigger.detached)
  49714. traverse(trigger.children[j], triggerParams, null, null);
  49715. }
  49716. }
  49717. };
  49718. ActionManager.GetTriggerName = function (trigger) {
  49719. switch (trigger) {
  49720. case 0: return "NothingTrigger";
  49721. case 1: return "OnPickTrigger";
  49722. case 2: return "OnLeftPickTrigger";
  49723. case 3: return "OnRightPickTrigger";
  49724. case 4: return "OnCenterPickTrigger";
  49725. case 5: return "OnPickDownTrigger";
  49726. case 6: return "OnPickUpTrigger";
  49727. case 7: return "OnLongPressTrigger";
  49728. case 8: return "OnPointerOverTrigger";
  49729. case 9: return "OnPointerOutTrigger";
  49730. case 10: return "OnEveryFrameTrigger";
  49731. case 11: return "OnIntersectionEnterTrigger";
  49732. case 12: return "OnIntersectionExitTrigger";
  49733. case 13: return "OnKeyDownTrigger";
  49734. case 14: return "OnKeyUpTrigger";
  49735. case 15: return "OnPickOutTrigger";
  49736. default: return "";
  49737. }
  49738. };
  49739. // Statics
  49740. ActionManager._NothingTrigger = 0;
  49741. ActionManager._OnPickTrigger = 1;
  49742. ActionManager._OnLeftPickTrigger = 2;
  49743. ActionManager._OnRightPickTrigger = 3;
  49744. ActionManager._OnCenterPickTrigger = 4;
  49745. ActionManager._OnPickDownTrigger = 5;
  49746. ActionManager._OnDoublePickTrigger = 6;
  49747. ActionManager._OnPickUpTrigger = 7;
  49748. ActionManager._OnLongPressTrigger = 8;
  49749. ActionManager._OnPointerOverTrigger = 9;
  49750. ActionManager._OnPointerOutTrigger = 10;
  49751. ActionManager._OnEveryFrameTrigger = 11;
  49752. ActionManager._OnIntersectionEnterTrigger = 12;
  49753. ActionManager._OnIntersectionExitTrigger = 13;
  49754. ActionManager._OnKeyDownTrigger = 14;
  49755. ActionManager._OnKeyUpTrigger = 15;
  49756. ActionManager._OnPickOutTrigger = 16;
  49757. ActionManager.Triggers = {};
  49758. return ActionManager;
  49759. }());
  49760. BABYLON.ActionManager = ActionManager;
  49761. })(BABYLON || (BABYLON = {}));
  49762. //# sourceMappingURL=babylon.actionManager.js.map
  49763. "use strict";
  49764. var BABYLON;
  49765. (function (BABYLON) {
  49766. var InterpolateValueAction = /** @class */ (function (_super) {
  49767. __extends(InterpolateValueAction, _super);
  49768. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49769. if (duration === void 0) { duration = 1000; }
  49770. var _this = _super.call(this, triggerOptions, condition) || this;
  49771. _this.propertyPath = propertyPath;
  49772. _this.value = value;
  49773. _this.duration = duration;
  49774. _this.stopOtherAnimations = stopOtherAnimations;
  49775. _this.onInterpolationDone = onInterpolationDone;
  49776. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49777. _this._target = _this._effectiveTarget = target;
  49778. return _this;
  49779. }
  49780. InterpolateValueAction.prototype._prepare = function () {
  49781. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49782. this._property = this._getProperty(this.propertyPath);
  49783. };
  49784. InterpolateValueAction.prototype.execute = function () {
  49785. var _this = this;
  49786. var scene = this._actionManager.getScene();
  49787. var keys = [
  49788. {
  49789. frame: 0,
  49790. value: this._effectiveTarget[this._property]
  49791. }, {
  49792. frame: 100,
  49793. value: this.value
  49794. }
  49795. ];
  49796. var dataType;
  49797. if (typeof this.value === "number") {
  49798. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49799. }
  49800. else if (this.value instanceof BABYLON.Color3) {
  49801. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49802. }
  49803. else if (this.value instanceof BABYLON.Vector3) {
  49804. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49805. }
  49806. else if (this.value instanceof BABYLON.Matrix) {
  49807. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49808. }
  49809. else if (this.value instanceof BABYLON.Quaternion) {
  49810. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49811. }
  49812. else {
  49813. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49814. return;
  49815. }
  49816. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49817. animation.setKeys(keys);
  49818. if (this.stopOtherAnimations) {
  49819. scene.stopAnimation(this._effectiveTarget);
  49820. }
  49821. var wrapper = function () {
  49822. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49823. if (_this.onInterpolationDone) {
  49824. _this.onInterpolationDone();
  49825. }
  49826. };
  49827. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49828. };
  49829. InterpolateValueAction.prototype.serialize = function (parent) {
  49830. return _super.prototype._serialize.call(this, {
  49831. name: "InterpolateValueAction",
  49832. properties: [
  49833. BABYLON.Action._GetTargetProperty(this._target),
  49834. { name: "propertyPath", value: this.propertyPath },
  49835. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49836. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49837. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49838. ]
  49839. }, parent);
  49840. };
  49841. return InterpolateValueAction;
  49842. }(BABYLON.Action));
  49843. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49844. })(BABYLON || (BABYLON = {}));
  49845. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49846. "use strict";
  49847. var BABYLON;
  49848. (function (BABYLON) {
  49849. var SwitchBooleanAction = /** @class */ (function (_super) {
  49850. __extends(SwitchBooleanAction, _super);
  49851. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49852. var _this = _super.call(this, triggerOptions, condition) || this;
  49853. _this.propertyPath = propertyPath;
  49854. _this._target = _this._effectiveTarget = target;
  49855. return _this;
  49856. }
  49857. SwitchBooleanAction.prototype._prepare = function () {
  49858. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49859. this._property = this._getProperty(this.propertyPath);
  49860. };
  49861. SwitchBooleanAction.prototype.execute = function () {
  49862. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49863. };
  49864. SwitchBooleanAction.prototype.serialize = function (parent) {
  49865. return _super.prototype._serialize.call(this, {
  49866. name: "SwitchBooleanAction",
  49867. properties: [
  49868. BABYLON.Action._GetTargetProperty(this._target),
  49869. { name: "propertyPath", value: this.propertyPath }
  49870. ]
  49871. }, parent);
  49872. };
  49873. return SwitchBooleanAction;
  49874. }(BABYLON.Action));
  49875. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49876. var SetStateAction = /** @class */ (function (_super) {
  49877. __extends(SetStateAction, _super);
  49878. function SetStateAction(triggerOptions, target, value, condition) {
  49879. var _this = _super.call(this, triggerOptions, condition) || this;
  49880. _this.value = value;
  49881. _this._target = target;
  49882. return _this;
  49883. }
  49884. SetStateAction.prototype.execute = function () {
  49885. this._target.state = this.value;
  49886. };
  49887. SetStateAction.prototype.serialize = function (parent) {
  49888. return _super.prototype._serialize.call(this, {
  49889. name: "SetStateAction",
  49890. properties: [
  49891. BABYLON.Action._GetTargetProperty(this._target),
  49892. { name: "value", value: this.value }
  49893. ]
  49894. }, parent);
  49895. };
  49896. return SetStateAction;
  49897. }(BABYLON.Action));
  49898. BABYLON.SetStateAction = SetStateAction;
  49899. var SetValueAction = /** @class */ (function (_super) {
  49900. __extends(SetValueAction, _super);
  49901. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49902. var _this = _super.call(this, triggerOptions, condition) || this;
  49903. _this.propertyPath = propertyPath;
  49904. _this.value = value;
  49905. _this._target = _this._effectiveTarget = target;
  49906. return _this;
  49907. }
  49908. SetValueAction.prototype._prepare = function () {
  49909. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49910. this._property = this._getProperty(this.propertyPath);
  49911. };
  49912. SetValueAction.prototype.execute = function () {
  49913. this._effectiveTarget[this._property] = this.value;
  49914. if (this._target.markAsDirty) {
  49915. this._target.markAsDirty(this._property);
  49916. }
  49917. };
  49918. SetValueAction.prototype.serialize = function (parent) {
  49919. return _super.prototype._serialize.call(this, {
  49920. name: "SetValueAction",
  49921. properties: [
  49922. BABYLON.Action._GetTargetProperty(this._target),
  49923. { name: "propertyPath", value: this.propertyPath },
  49924. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49925. ]
  49926. }, parent);
  49927. };
  49928. return SetValueAction;
  49929. }(BABYLON.Action));
  49930. BABYLON.SetValueAction = SetValueAction;
  49931. var IncrementValueAction = /** @class */ (function (_super) {
  49932. __extends(IncrementValueAction, _super);
  49933. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49934. var _this = _super.call(this, triggerOptions, condition) || this;
  49935. _this.propertyPath = propertyPath;
  49936. _this.value = value;
  49937. _this._target = _this._effectiveTarget = target;
  49938. return _this;
  49939. }
  49940. IncrementValueAction.prototype._prepare = function () {
  49941. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49942. this._property = this._getProperty(this.propertyPath);
  49943. if (typeof this._effectiveTarget[this._property] !== "number") {
  49944. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49945. }
  49946. };
  49947. IncrementValueAction.prototype.execute = function () {
  49948. this._effectiveTarget[this._property] += this.value;
  49949. if (this._target.markAsDirty) {
  49950. this._target.markAsDirty(this._property);
  49951. }
  49952. };
  49953. IncrementValueAction.prototype.serialize = function (parent) {
  49954. return _super.prototype._serialize.call(this, {
  49955. name: "IncrementValueAction",
  49956. properties: [
  49957. BABYLON.Action._GetTargetProperty(this._target),
  49958. { name: "propertyPath", value: this.propertyPath },
  49959. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49960. ]
  49961. }, parent);
  49962. };
  49963. return IncrementValueAction;
  49964. }(BABYLON.Action));
  49965. BABYLON.IncrementValueAction = IncrementValueAction;
  49966. var PlayAnimationAction = /** @class */ (function (_super) {
  49967. __extends(PlayAnimationAction, _super);
  49968. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49969. var _this = _super.call(this, triggerOptions, condition) || this;
  49970. _this.from = from;
  49971. _this.to = to;
  49972. _this.loop = loop;
  49973. _this._target = target;
  49974. return _this;
  49975. }
  49976. PlayAnimationAction.prototype._prepare = function () {
  49977. };
  49978. PlayAnimationAction.prototype.execute = function () {
  49979. var scene = this._actionManager.getScene();
  49980. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49981. };
  49982. PlayAnimationAction.prototype.serialize = function (parent) {
  49983. return _super.prototype._serialize.call(this, {
  49984. name: "PlayAnimationAction",
  49985. properties: [
  49986. BABYLON.Action._GetTargetProperty(this._target),
  49987. { name: "from", value: String(this.from) },
  49988. { name: "to", value: String(this.to) },
  49989. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49990. ]
  49991. }, parent);
  49992. };
  49993. return PlayAnimationAction;
  49994. }(BABYLON.Action));
  49995. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49996. var StopAnimationAction = /** @class */ (function (_super) {
  49997. __extends(StopAnimationAction, _super);
  49998. function StopAnimationAction(triggerOptions, target, condition) {
  49999. var _this = _super.call(this, triggerOptions, condition) || this;
  50000. _this._target = target;
  50001. return _this;
  50002. }
  50003. StopAnimationAction.prototype._prepare = function () {
  50004. };
  50005. StopAnimationAction.prototype.execute = function () {
  50006. var scene = this._actionManager.getScene();
  50007. scene.stopAnimation(this._target);
  50008. };
  50009. StopAnimationAction.prototype.serialize = function (parent) {
  50010. return _super.prototype._serialize.call(this, {
  50011. name: "StopAnimationAction",
  50012. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  50013. }, parent);
  50014. };
  50015. return StopAnimationAction;
  50016. }(BABYLON.Action));
  50017. BABYLON.StopAnimationAction = StopAnimationAction;
  50018. var DoNothingAction = /** @class */ (function (_super) {
  50019. __extends(DoNothingAction, _super);
  50020. function DoNothingAction(triggerOptions, condition) {
  50021. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  50022. return _super.call(this, triggerOptions, condition) || this;
  50023. }
  50024. DoNothingAction.prototype.execute = function () {
  50025. };
  50026. DoNothingAction.prototype.serialize = function (parent) {
  50027. return _super.prototype._serialize.call(this, {
  50028. name: "DoNothingAction",
  50029. properties: []
  50030. }, parent);
  50031. };
  50032. return DoNothingAction;
  50033. }(BABYLON.Action));
  50034. BABYLON.DoNothingAction = DoNothingAction;
  50035. var CombineAction = /** @class */ (function (_super) {
  50036. __extends(CombineAction, _super);
  50037. function CombineAction(triggerOptions, children, condition) {
  50038. var _this = _super.call(this, triggerOptions, condition) || this;
  50039. _this.children = children;
  50040. return _this;
  50041. }
  50042. CombineAction.prototype._prepare = function () {
  50043. for (var index = 0; index < this.children.length; index++) {
  50044. this.children[index]._actionManager = this._actionManager;
  50045. this.children[index]._prepare();
  50046. }
  50047. };
  50048. CombineAction.prototype.execute = function (evt) {
  50049. for (var index = 0; index < this.children.length; index++) {
  50050. this.children[index].execute(evt);
  50051. }
  50052. };
  50053. CombineAction.prototype.serialize = function (parent) {
  50054. var serializationObject = _super.prototype._serialize.call(this, {
  50055. name: "CombineAction",
  50056. properties: [],
  50057. combine: []
  50058. }, parent);
  50059. for (var i = 0; i < this.children.length; i++) {
  50060. serializationObject.combine.push(this.children[i].serialize(null));
  50061. }
  50062. return serializationObject;
  50063. };
  50064. return CombineAction;
  50065. }(BABYLON.Action));
  50066. BABYLON.CombineAction = CombineAction;
  50067. var ExecuteCodeAction = /** @class */ (function (_super) {
  50068. __extends(ExecuteCodeAction, _super);
  50069. function ExecuteCodeAction(triggerOptions, func, condition) {
  50070. var _this = _super.call(this, triggerOptions, condition) || this;
  50071. _this.func = func;
  50072. return _this;
  50073. }
  50074. ExecuteCodeAction.prototype.execute = function (evt) {
  50075. this.func(evt);
  50076. };
  50077. return ExecuteCodeAction;
  50078. }(BABYLON.Action));
  50079. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  50080. var SetParentAction = /** @class */ (function (_super) {
  50081. __extends(SetParentAction, _super);
  50082. function SetParentAction(triggerOptions, target, parent, condition) {
  50083. var _this = _super.call(this, triggerOptions, condition) || this;
  50084. _this._target = target;
  50085. _this._parent = parent;
  50086. return _this;
  50087. }
  50088. SetParentAction.prototype._prepare = function () {
  50089. };
  50090. SetParentAction.prototype.execute = function () {
  50091. if (this._target.parent === this._parent) {
  50092. return;
  50093. }
  50094. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  50095. invertParentWorldMatrix.invert();
  50096. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  50097. this._target.parent = this._parent;
  50098. };
  50099. SetParentAction.prototype.serialize = function (parent) {
  50100. return _super.prototype._serialize.call(this, {
  50101. name: "SetParentAction",
  50102. properties: [
  50103. BABYLON.Action._GetTargetProperty(this._target),
  50104. BABYLON.Action._GetTargetProperty(this._parent),
  50105. ]
  50106. }, parent);
  50107. };
  50108. return SetParentAction;
  50109. }(BABYLON.Action));
  50110. BABYLON.SetParentAction = SetParentAction;
  50111. var PlaySoundAction = /** @class */ (function (_super) {
  50112. __extends(PlaySoundAction, _super);
  50113. function PlaySoundAction(triggerOptions, sound, condition) {
  50114. var _this = _super.call(this, triggerOptions, condition) || this;
  50115. _this._sound = sound;
  50116. return _this;
  50117. }
  50118. PlaySoundAction.prototype._prepare = function () {
  50119. };
  50120. PlaySoundAction.prototype.execute = function () {
  50121. if (this._sound !== undefined)
  50122. this._sound.play();
  50123. };
  50124. PlaySoundAction.prototype.serialize = function (parent) {
  50125. return _super.prototype._serialize.call(this, {
  50126. name: "PlaySoundAction",
  50127. properties: [{ name: "sound", value: this._sound.name }]
  50128. }, parent);
  50129. };
  50130. return PlaySoundAction;
  50131. }(BABYLON.Action));
  50132. BABYLON.PlaySoundAction = PlaySoundAction;
  50133. var StopSoundAction = /** @class */ (function (_super) {
  50134. __extends(StopSoundAction, _super);
  50135. function StopSoundAction(triggerOptions, sound, condition) {
  50136. var _this = _super.call(this, triggerOptions, condition) || this;
  50137. _this._sound = sound;
  50138. return _this;
  50139. }
  50140. StopSoundAction.prototype._prepare = function () {
  50141. };
  50142. StopSoundAction.prototype.execute = function () {
  50143. if (this._sound !== undefined)
  50144. this._sound.stop();
  50145. };
  50146. StopSoundAction.prototype.serialize = function (parent) {
  50147. return _super.prototype._serialize.call(this, {
  50148. name: "StopSoundAction",
  50149. properties: [{ name: "sound", value: this._sound.name }]
  50150. }, parent);
  50151. };
  50152. return StopSoundAction;
  50153. }(BABYLON.Action));
  50154. BABYLON.StopSoundAction = StopSoundAction;
  50155. })(BABYLON || (BABYLON = {}));
  50156. //# sourceMappingURL=babylon.directActions.js.map
  50157. "use strict";
  50158. var BABYLON;
  50159. (function (BABYLON) {
  50160. var SpriteManager = /** @class */ (function () {
  50161. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  50162. if (epsilon === void 0) { epsilon = 0.01; }
  50163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50164. this.name = name;
  50165. this.sprites = new Array();
  50166. this.renderingGroupId = 0;
  50167. this.layerMask = 0x0FFFFFFF;
  50168. this.fogEnabled = true;
  50169. this.isPickable = false;
  50170. /**
  50171. * An event triggered when the manager is disposed.
  50172. * @type {BABYLON.Observable}
  50173. */
  50174. this.onDisposeObservable = new BABYLON.Observable();
  50175. this._vertexBuffers = {};
  50176. this._capacity = capacity;
  50177. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  50178. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50179. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50180. if (cellSize.width && cellSize.height) {
  50181. this.cellWidth = cellSize.width;
  50182. this.cellHeight = cellSize.height;
  50183. }
  50184. else if (cellSize !== undefined) {
  50185. this.cellWidth = cellSize;
  50186. this.cellHeight = cellSize;
  50187. }
  50188. else {
  50189. return;
  50190. }
  50191. this._epsilon = epsilon;
  50192. this._scene = scene;
  50193. this._scene.spriteManagers.push(this);
  50194. var indices = [];
  50195. var index = 0;
  50196. for (var count = 0; count < capacity; count++) {
  50197. indices.push(index);
  50198. indices.push(index + 1);
  50199. indices.push(index + 2);
  50200. indices.push(index);
  50201. indices.push(index + 2);
  50202. indices.push(index + 3);
  50203. index += 4;
  50204. }
  50205. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  50206. // VBO
  50207. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  50208. this._vertexData = new Float32Array(capacity * 16 * 4);
  50209. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  50210. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  50211. var options = this._buffer.createVertexBuffer("options", 4, 4);
  50212. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  50213. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  50214. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50215. this._vertexBuffers["options"] = options;
  50216. this._vertexBuffers["cellInfo"] = cellInfo;
  50217. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50218. // Effects
  50219. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  50220. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  50221. }
  50222. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50223. set: function (callback) {
  50224. if (this._onDisposeObserver) {
  50225. this.onDisposeObservable.remove(this._onDisposeObserver);
  50226. }
  50227. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50228. },
  50229. enumerable: true,
  50230. configurable: true
  50231. });
  50232. Object.defineProperty(SpriteManager.prototype, "texture", {
  50233. get: function () {
  50234. return this._spriteTexture;
  50235. },
  50236. set: function (value) {
  50237. this._spriteTexture = value;
  50238. },
  50239. enumerable: true,
  50240. configurable: true
  50241. });
  50242. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50243. var arrayOffset = index * 16;
  50244. if (offsetX === 0)
  50245. offsetX = this._epsilon;
  50246. else if (offsetX === 1)
  50247. offsetX = 1 - this._epsilon;
  50248. if (offsetY === 0)
  50249. offsetY = this._epsilon;
  50250. else if (offsetY === 1)
  50251. offsetY = 1 - this._epsilon;
  50252. this._vertexData[arrayOffset] = sprite.position.x;
  50253. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50254. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50255. this._vertexData[arrayOffset + 3] = sprite.angle;
  50256. this._vertexData[arrayOffset + 4] = sprite.width;
  50257. this._vertexData[arrayOffset + 5] = sprite.height;
  50258. this._vertexData[arrayOffset + 6] = offsetX;
  50259. this._vertexData[arrayOffset + 7] = offsetY;
  50260. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50261. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50262. var offset = (sprite.cellIndex / rowSize) >> 0;
  50263. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50264. this._vertexData[arrayOffset + 11] = offset;
  50265. // Color
  50266. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50267. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50268. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50269. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50270. };
  50271. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50272. var count = Math.min(this._capacity, this.sprites.length);
  50273. var min = BABYLON.Vector3.Zero();
  50274. var max = BABYLON.Vector3.Zero();
  50275. var distance = Number.MAX_VALUE;
  50276. var currentSprite = null;
  50277. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50278. var cameraView = camera.getViewMatrix();
  50279. for (var index = 0; index < count; index++) {
  50280. var sprite = this.sprites[index];
  50281. if (!sprite) {
  50282. continue;
  50283. }
  50284. if (predicate) {
  50285. if (!predicate(sprite)) {
  50286. continue;
  50287. }
  50288. }
  50289. else if (!sprite.isPickable) {
  50290. continue;
  50291. }
  50292. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50293. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50294. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50295. if (ray.intersectsBoxMinMax(min, max)) {
  50296. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50297. if (distance > currentDistance) {
  50298. distance = currentDistance;
  50299. currentSprite = sprite;
  50300. if (fastCheck) {
  50301. break;
  50302. }
  50303. }
  50304. }
  50305. }
  50306. if (currentSprite) {
  50307. var result = new BABYLON.PickingInfo();
  50308. result.hit = true;
  50309. result.pickedSprite = currentSprite;
  50310. result.distance = distance;
  50311. return result;
  50312. }
  50313. return null;
  50314. };
  50315. SpriteManager.prototype.render = function () {
  50316. // Check
  50317. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50318. return;
  50319. var engine = this._scene.getEngine();
  50320. var baseSize = this._spriteTexture.getBaseSize();
  50321. // Sprites
  50322. var deltaTime = engine.getDeltaTime();
  50323. var max = Math.min(this._capacity, this.sprites.length);
  50324. var rowSize = baseSize.width / this.cellWidth;
  50325. var offset = 0;
  50326. for (var index = 0; index < max; index++) {
  50327. var sprite = this.sprites[index];
  50328. if (!sprite) {
  50329. continue;
  50330. }
  50331. sprite._animate(deltaTime);
  50332. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50333. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50334. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50335. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50336. }
  50337. this._buffer.update(this._vertexData);
  50338. // Render
  50339. var effect = this._effectBase;
  50340. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50341. effect = this._effectFog;
  50342. }
  50343. engine.enableEffect(effect);
  50344. var viewMatrix = this._scene.getViewMatrix();
  50345. effect.setTexture("diffuseSampler", this._spriteTexture);
  50346. effect.setMatrix("view", viewMatrix);
  50347. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50348. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50349. // Fog
  50350. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50351. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50352. effect.setColor3("vFogColor", this._scene.fogColor);
  50353. }
  50354. // VBOs
  50355. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50356. // Draw order
  50357. engine.setDepthFunctionToLessOrEqual();
  50358. effect.setBool("alphaTest", true);
  50359. engine.setColorWrite(false);
  50360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50361. engine.setColorWrite(true);
  50362. effect.setBool("alphaTest", false);
  50363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50364. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50366. };
  50367. SpriteManager.prototype.dispose = function () {
  50368. if (this._buffer) {
  50369. this._buffer.dispose();
  50370. this._buffer = null;
  50371. }
  50372. if (this._indexBuffer) {
  50373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50374. this._indexBuffer = null;
  50375. }
  50376. if (this._spriteTexture) {
  50377. this._spriteTexture.dispose();
  50378. this._spriteTexture = null;
  50379. }
  50380. // Remove from scene
  50381. var index = this._scene.spriteManagers.indexOf(this);
  50382. this._scene.spriteManagers.splice(index, 1);
  50383. // Callback
  50384. this.onDisposeObservable.notifyObservers(this);
  50385. this.onDisposeObservable.clear();
  50386. };
  50387. return SpriteManager;
  50388. }());
  50389. BABYLON.SpriteManager = SpriteManager;
  50390. })(BABYLON || (BABYLON = {}));
  50391. //# sourceMappingURL=babylon.spriteManager.js.map
  50392. "use strict";
  50393. var BABYLON;
  50394. (function (BABYLON) {
  50395. var Sprite = /** @class */ (function () {
  50396. function Sprite(name, manager) {
  50397. this.name = name;
  50398. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50399. this.width = 1.0;
  50400. this.height = 1.0;
  50401. this.angle = 0;
  50402. this.cellIndex = 0;
  50403. this.invertU = 0;
  50404. this.invertV = 0;
  50405. this.animations = new Array();
  50406. this.isPickable = false;
  50407. this._animationStarted = false;
  50408. this._loopAnimation = false;
  50409. this._fromIndex = 0;
  50410. this._toIndex = 0;
  50411. this._delay = 0;
  50412. this._direction = 1;
  50413. this._time = 0;
  50414. this._manager = manager;
  50415. this._manager.sprites.push(this);
  50416. this.position = BABYLON.Vector3.Zero();
  50417. }
  50418. Object.defineProperty(Sprite.prototype, "size", {
  50419. get: function () {
  50420. return this.width;
  50421. },
  50422. set: function (value) {
  50423. this.width = value;
  50424. this.height = value;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50430. this._fromIndex = from;
  50431. this._toIndex = to;
  50432. this._loopAnimation = loop;
  50433. this._delay = delay;
  50434. this._animationStarted = true;
  50435. this._direction = from < to ? 1 : -1;
  50436. this.cellIndex = from;
  50437. this._time = 0;
  50438. this._onAnimationEnd = onAnimationEnd;
  50439. };
  50440. Sprite.prototype.stopAnimation = function () {
  50441. this._animationStarted = false;
  50442. };
  50443. Sprite.prototype._animate = function (deltaTime) {
  50444. if (!this._animationStarted)
  50445. return;
  50446. this._time += deltaTime;
  50447. if (this._time > this._delay) {
  50448. this._time = this._time % this._delay;
  50449. this.cellIndex += this._direction;
  50450. if (this.cellIndex > this._toIndex) {
  50451. if (this._loopAnimation) {
  50452. this.cellIndex = this._fromIndex;
  50453. }
  50454. else {
  50455. this.cellIndex = this._toIndex;
  50456. this._animationStarted = false;
  50457. if (this._onAnimationEnd) {
  50458. this._onAnimationEnd();
  50459. }
  50460. if (this.disposeWhenFinishedAnimating) {
  50461. this.dispose();
  50462. }
  50463. }
  50464. }
  50465. }
  50466. };
  50467. Sprite.prototype.dispose = function () {
  50468. for (var i = 0; i < this._manager.sprites.length; i++) {
  50469. if (this._manager.sprites[i] == this) {
  50470. this._manager.sprites.splice(i, 1);
  50471. }
  50472. }
  50473. };
  50474. return Sprite;
  50475. }());
  50476. BABYLON.Sprite = Sprite;
  50477. })(BABYLON || (BABYLON = {}));
  50478. //# sourceMappingURL=babylon.sprite.js.map
  50479. "use strict";
  50480. var BABYLON;
  50481. (function (BABYLON) {
  50482. var IntersectionInfo = /** @class */ (function () {
  50483. function IntersectionInfo(bu, bv, distance) {
  50484. this.bu = bu;
  50485. this.bv = bv;
  50486. this.distance = distance;
  50487. this.faceId = 0;
  50488. this.subMeshId = 0;
  50489. }
  50490. return IntersectionInfo;
  50491. }());
  50492. BABYLON.IntersectionInfo = IntersectionInfo;
  50493. var PickingInfo = /** @class */ (function () {
  50494. function PickingInfo() {
  50495. this.hit = false;
  50496. this.distance = 0;
  50497. this.pickedPoint = null;
  50498. this.pickedMesh = null;
  50499. this.bu = 0;
  50500. this.bv = 0;
  50501. this.faceId = -1;
  50502. this.subMeshId = 0;
  50503. this.pickedSprite = null;
  50504. }
  50505. // Methods
  50506. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50507. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50508. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50509. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50510. return null;
  50511. }
  50512. var indices = this.pickedMesh.getIndices();
  50513. if (!indices) {
  50514. return null;
  50515. }
  50516. var result;
  50517. if (useVerticesNormals) {
  50518. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50519. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50520. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50521. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50522. normal0 = normal0.scale(this.bu);
  50523. normal1 = normal1.scale(this.bv);
  50524. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50525. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50526. }
  50527. else {
  50528. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50529. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50530. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50531. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50532. var p1p2 = vertex1.subtract(vertex2);
  50533. var p3p2 = vertex3.subtract(vertex2);
  50534. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50535. }
  50536. if (useWorldCoordinates) {
  50537. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50538. }
  50539. return BABYLON.Vector3.Normalize(result);
  50540. };
  50541. PickingInfo.prototype.getTextureCoordinates = function () {
  50542. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50543. return null;
  50544. }
  50545. var indices = this.pickedMesh.getIndices();
  50546. if (!indices) {
  50547. return null;
  50548. }
  50549. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50550. if (!uvs) {
  50551. return null;
  50552. }
  50553. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50554. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50555. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50556. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50557. uv1 = uv1.scale(this.bu);
  50558. uv2 = uv2.scale(this.bv);
  50559. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50560. };
  50561. return PickingInfo;
  50562. }());
  50563. BABYLON.PickingInfo = PickingInfo;
  50564. })(BABYLON || (BABYLON = {}));
  50565. //# sourceMappingURL=babylon.pickingInfo.js.map
  50566. "use strict";
  50567. var BABYLON;
  50568. (function (BABYLON) {
  50569. var Ray = /** @class */ (function () {
  50570. function Ray(origin, direction, length) {
  50571. if (length === void 0) { length = Number.MAX_VALUE; }
  50572. this.origin = origin;
  50573. this.direction = direction;
  50574. this.length = length;
  50575. }
  50576. // Methods
  50577. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50578. var d = 0.0;
  50579. var maxValue = Number.MAX_VALUE;
  50580. var inv;
  50581. var min;
  50582. var max;
  50583. var temp;
  50584. if (Math.abs(this.direction.x) < 0.0000001) {
  50585. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50586. return false;
  50587. }
  50588. }
  50589. else {
  50590. inv = 1.0 / this.direction.x;
  50591. min = (minimum.x - this.origin.x) * inv;
  50592. max = (maximum.x - this.origin.x) * inv;
  50593. if (max === -Infinity) {
  50594. max = Infinity;
  50595. }
  50596. if (min > max) {
  50597. temp = min;
  50598. min = max;
  50599. max = temp;
  50600. }
  50601. d = Math.max(min, d);
  50602. maxValue = Math.min(max, maxValue);
  50603. if (d > maxValue) {
  50604. return false;
  50605. }
  50606. }
  50607. if (Math.abs(this.direction.y) < 0.0000001) {
  50608. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50609. return false;
  50610. }
  50611. }
  50612. else {
  50613. inv = 1.0 / this.direction.y;
  50614. min = (minimum.y - this.origin.y) * inv;
  50615. max = (maximum.y - this.origin.y) * inv;
  50616. if (max === -Infinity) {
  50617. max = Infinity;
  50618. }
  50619. if (min > max) {
  50620. temp = min;
  50621. min = max;
  50622. max = temp;
  50623. }
  50624. d = Math.max(min, d);
  50625. maxValue = Math.min(max, maxValue);
  50626. if (d > maxValue) {
  50627. return false;
  50628. }
  50629. }
  50630. if (Math.abs(this.direction.z) < 0.0000001) {
  50631. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50632. return false;
  50633. }
  50634. }
  50635. else {
  50636. inv = 1.0 / this.direction.z;
  50637. min = (minimum.z - this.origin.z) * inv;
  50638. max = (maximum.z - this.origin.z) * inv;
  50639. if (max === -Infinity) {
  50640. max = Infinity;
  50641. }
  50642. if (min > max) {
  50643. temp = min;
  50644. min = max;
  50645. max = temp;
  50646. }
  50647. d = Math.max(min, d);
  50648. maxValue = Math.min(max, maxValue);
  50649. if (d > maxValue) {
  50650. return false;
  50651. }
  50652. }
  50653. return true;
  50654. };
  50655. Ray.prototype.intersectsBox = function (box) {
  50656. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50657. };
  50658. Ray.prototype.intersectsSphere = function (sphere) {
  50659. var x = sphere.center.x - this.origin.x;
  50660. var y = sphere.center.y - this.origin.y;
  50661. var z = sphere.center.z - this.origin.z;
  50662. var pyth = (x * x) + (y * y) + (z * z);
  50663. var rr = sphere.radius * sphere.radius;
  50664. if (pyth <= rr) {
  50665. return true;
  50666. }
  50667. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50668. if (dot < 0.0) {
  50669. return false;
  50670. }
  50671. var temp = pyth - (dot * dot);
  50672. return temp <= rr;
  50673. };
  50674. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50675. if (!this._edge1) {
  50676. this._edge1 = BABYLON.Vector3.Zero();
  50677. this._edge2 = BABYLON.Vector3.Zero();
  50678. this._pvec = BABYLON.Vector3.Zero();
  50679. this._tvec = BABYLON.Vector3.Zero();
  50680. this._qvec = BABYLON.Vector3.Zero();
  50681. }
  50682. vertex1.subtractToRef(vertex0, this._edge1);
  50683. vertex2.subtractToRef(vertex0, this._edge2);
  50684. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50685. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50686. if (det === 0) {
  50687. return null;
  50688. }
  50689. var invdet = 1 / det;
  50690. this.origin.subtractToRef(vertex0, this._tvec);
  50691. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50692. if (bu < 0 || bu > 1.0) {
  50693. return null;
  50694. }
  50695. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50696. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50697. if (bv < 0 || bu + bv > 1.0) {
  50698. return null;
  50699. }
  50700. //check if the distance is longer than the predefined length.
  50701. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50702. if (distance > this.length) {
  50703. return null;
  50704. }
  50705. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50706. };
  50707. Ray.prototype.intersectsPlane = function (plane) {
  50708. var distance;
  50709. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50710. if (Math.abs(result1) < 9.99999997475243E-07) {
  50711. return null;
  50712. }
  50713. else {
  50714. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50715. distance = (-plane.d - result2) / result1;
  50716. if (distance < 0.0) {
  50717. if (distance < -9.99999997475243E-07) {
  50718. return null;
  50719. }
  50720. else {
  50721. return 0;
  50722. }
  50723. }
  50724. return distance;
  50725. }
  50726. };
  50727. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50728. var tm = BABYLON.Tmp.Matrix[0];
  50729. mesh.getWorldMatrix().invertToRef(tm);
  50730. if (this._tmpRay) {
  50731. Ray.TransformToRef(this, tm, this._tmpRay);
  50732. }
  50733. else {
  50734. this._tmpRay = Ray.Transform(this, tm);
  50735. }
  50736. return mesh.intersects(this._tmpRay, fastCheck);
  50737. };
  50738. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50739. if (results) {
  50740. results.length = 0;
  50741. }
  50742. else {
  50743. results = [];
  50744. }
  50745. for (var i = 0; i < meshes.length; i++) {
  50746. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50747. if (pickInfo.hit) {
  50748. results.push(pickInfo);
  50749. }
  50750. }
  50751. results.sort(this._comparePickingInfo);
  50752. return results;
  50753. };
  50754. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50755. if (pickingInfoA.distance < pickingInfoB.distance) {
  50756. return -1;
  50757. }
  50758. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50759. return 1;
  50760. }
  50761. else {
  50762. return 0;
  50763. }
  50764. };
  50765. /**
  50766. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50767. * @param sega the first point of the segment to test the intersection against
  50768. * @param segb the second point of the segment to test the intersection against
  50769. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50770. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50771. */
  50772. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50773. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50774. var u = segb.subtract(sega);
  50775. var v = rsegb.subtract(this.origin);
  50776. var w = sega.subtract(this.origin);
  50777. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50778. var b = BABYLON.Vector3.Dot(u, v);
  50779. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50780. var d = BABYLON.Vector3.Dot(u, w);
  50781. var e = BABYLON.Vector3.Dot(v, w);
  50782. var D = a * c - b * b; // always >= 0
  50783. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50784. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50785. // compute the line parameters of the two closest points
  50786. if (D < Ray.smallnum) {
  50787. sN = 0.0; // force using point P0 on segment S1
  50788. sD = 1.0; // to prevent possible division by 0.0 later
  50789. tN = e;
  50790. tD = c;
  50791. }
  50792. else {
  50793. sN = (b * e - c * d);
  50794. tN = (a * e - b * d);
  50795. if (sN < 0.0) {
  50796. sN = 0.0;
  50797. tN = e;
  50798. tD = c;
  50799. }
  50800. else if (sN > sD) {
  50801. sN = sD;
  50802. tN = e + b;
  50803. tD = c;
  50804. }
  50805. }
  50806. if (tN < 0.0) {
  50807. tN = 0.0;
  50808. // recompute sc for this edge
  50809. if (-d < 0.0) {
  50810. sN = 0.0;
  50811. }
  50812. else if (-d > a)
  50813. sN = sD;
  50814. else {
  50815. sN = -d;
  50816. sD = a;
  50817. }
  50818. }
  50819. else if (tN > tD) {
  50820. tN = tD;
  50821. // recompute sc for this edge
  50822. if ((-d + b) < 0.0) {
  50823. sN = 0;
  50824. }
  50825. else if ((-d + b) > a) {
  50826. sN = sD;
  50827. }
  50828. else {
  50829. sN = (-d + b);
  50830. sD = a;
  50831. }
  50832. }
  50833. // finally do the division to get sc and tc
  50834. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50835. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50836. // get the difference of the two closest points
  50837. var qtc = v.multiplyByFloats(tc, tc, tc);
  50838. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50839. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50840. if (isIntersected) {
  50841. return qtc.length();
  50842. }
  50843. return -1;
  50844. };
  50845. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50846. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50847. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50848. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50849. this.direction.normalize();
  50850. return this;
  50851. };
  50852. // Statics
  50853. Ray.Zero = function () {
  50854. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50855. };
  50856. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50857. var result = Ray.Zero();
  50858. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50859. };
  50860. /**
  50861. * 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
  50862. * transformed to the given world matrix.
  50863. * @param origin The origin point
  50864. * @param end The end point
  50865. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50866. */
  50867. Ray.CreateNewFromTo = function (origin, end, world) {
  50868. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50869. var direction = end.subtract(origin);
  50870. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50871. direction.normalize();
  50872. return Ray.Transform(new Ray(origin, direction, length), world);
  50873. };
  50874. Ray.Transform = function (ray, matrix) {
  50875. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50876. Ray.TransformToRef(ray, matrix, result);
  50877. return result;
  50878. };
  50879. Ray.TransformToRef = function (ray, matrix, result) {
  50880. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50881. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50882. result.length = ray.length;
  50883. var dir = result.direction;
  50884. var len = dir.length();
  50885. if (!(len === 0 || len === 1)) {
  50886. var num = 1.0 / len;
  50887. dir.x *= num;
  50888. dir.y *= num;
  50889. dir.z *= num;
  50890. result.length *= len;
  50891. }
  50892. };
  50893. Ray.smallnum = 0.00000001;
  50894. Ray.rayl = 10e8;
  50895. return Ray;
  50896. }());
  50897. BABYLON.Ray = Ray;
  50898. })(BABYLON || (BABYLON = {}));
  50899. //# sourceMappingURL=babylon.ray.js.map
  50900. "use strict";
  50901. var BABYLON;
  50902. (function (BABYLON) {
  50903. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50904. if (boxMin.x > sphereCenter.x + sphereRadius)
  50905. return false;
  50906. if (sphereCenter.x - sphereRadius > boxMax.x)
  50907. return false;
  50908. if (boxMin.y > sphereCenter.y + sphereRadius)
  50909. return false;
  50910. if (sphereCenter.y - sphereRadius > boxMax.y)
  50911. return false;
  50912. if (boxMin.z > sphereCenter.z + sphereRadius)
  50913. return false;
  50914. if (sphereCenter.z - sphereRadius > boxMax.z)
  50915. return false;
  50916. return true;
  50917. };
  50918. var getLowestRoot = (function () {
  50919. var result = { root: 0, found: false };
  50920. return function (a, b, c, maxR) {
  50921. result.root = 0;
  50922. result.found = false;
  50923. var determinant = b * b - 4.0 * a * c;
  50924. if (determinant < 0)
  50925. return result;
  50926. var sqrtD = Math.sqrt(determinant);
  50927. var r1 = (-b - sqrtD) / (2.0 * a);
  50928. var r2 = (-b + sqrtD) / (2.0 * a);
  50929. if (r1 > r2) {
  50930. var temp = r2;
  50931. r2 = r1;
  50932. r1 = temp;
  50933. }
  50934. if (r1 > 0 && r1 < maxR) {
  50935. result.root = r1;
  50936. result.found = true;
  50937. return result;
  50938. }
  50939. if (r2 > 0 && r2 < maxR) {
  50940. result.root = r2;
  50941. result.found = true;
  50942. return result;
  50943. }
  50944. return result;
  50945. };
  50946. })();
  50947. var Collider = /** @class */ (function () {
  50948. function Collider() {
  50949. this._collisionPoint = BABYLON.Vector3.Zero();
  50950. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50951. this._tempVector = BABYLON.Vector3.Zero();
  50952. this._tempVector2 = BABYLON.Vector3.Zero();
  50953. this._tempVector3 = BABYLON.Vector3.Zero();
  50954. this._tempVector4 = BABYLON.Vector3.Zero();
  50955. this._edge = BABYLON.Vector3.Zero();
  50956. this._baseToVertex = BABYLON.Vector3.Zero();
  50957. this._destinationPoint = BABYLON.Vector3.Zero();
  50958. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50959. this._displacementVector = BABYLON.Vector3.Zero();
  50960. this._radius = BABYLON.Vector3.One();
  50961. this._retry = 0;
  50962. this._basePointWorld = BABYLON.Vector3.Zero();
  50963. this._velocityWorld = BABYLON.Vector3.Zero();
  50964. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50965. this._collisionMask = -1;
  50966. }
  50967. Object.defineProperty(Collider.prototype, "collisionMask", {
  50968. get: function () {
  50969. return this._collisionMask;
  50970. },
  50971. set: function (mask) {
  50972. this._collisionMask = !isNaN(mask) ? mask : -1;
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50978. /**
  50979. * Gets the plane normal used to compute the sliding response (in local space)
  50980. */
  50981. get: function () {
  50982. return this._slidePlaneNormal;
  50983. },
  50984. enumerable: true,
  50985. configurable: true
  50986. });
  50987. // Methods
  50988. Collider.prototype._initialize = function (source, dir, e) {
  50989. this._velocity = dir;
  50990. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50991. this._basePoint = source;
  50992. source.multiplyToRef(this._radius, this._basePointWorld);
  50993. dir.multiplyToRef(this._radius, this._velocityWorld);
  50994. this._velocityWorldLength = this._velocityWorld.length();
  50995. this._epsilon = e;
  50996. this.collisionFound = false;
  50997. };
  50998. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50999. pa.subtractToRef(point, this._tempVector);
  51000. pb.subtractToRef(point, this._tempVector2);
  51001. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  51002. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51003. if (d < 0)
  51004. return false;
  51005. pc.subtractToRef(point, this._tempVector3);
  51006. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  51007. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51008. if (d < 0)
  51009. return false;
  51010. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  51011. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  51012. return d >= 0;
  51013. };
  51014. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  51015. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  51016. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  51017. if (distance > this._velocityWorldLength + max + sphereRadius) {
  51018. return false;
  51019. }
  51020. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  51021. return false;
  51022. return true;
  51023. };
  51024. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  51025. var t0;
  51026. var embeddedInPlane = false;
  51027. //defensive programming, actually not needed.
  51028. if (!trianglePlaneArray) {
  51029. trianglePlaneArray = [];
  51030. }
  51031. if (!trianglePlaneArray[faceIndex]) {
  51032. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  51033. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  51034. }
  51035. var trianglePlane = trianglePlaneArray[faceIndex];
  51036. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  51037. return;
  51038. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  51039. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  51040. if (normalDotVelocity == 0) {
  51041. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  51042. return;
  51043. embeddedInPlane = true;
  51044. t0 = 0;
  51045. }
  51046. else {
  51047. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51048. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  51049. if (t0 > t1) {
  51050. var temp = t1;
  51051. t1 = t0;
  51052. t0 = temp;
  51053. }
  51054. if (t0 > 1.0 || t1 < 0.0)
  51055. return;
  51056. if (t0 < 0)
  51057. t0 = 0;
  51058. if (t0 > 1.0)
  51059. t0 = 1.0;
  51060. }
  51061. this._collisionPoint.copyFromFloats(0, 0, 0);
  51062. var found = false;
  51063. var t = 1.0;
  51064. if (!embeddedInPlane) {
  51065. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  51066. this._velocity.scaleToRef(t0, this._tempVector);
  51067. this._planeIntersectionPoint.addInPlace(this._tempVector);
  51068. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  51069. found = true;
  51070. t = t0;
  51071. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  51072. }
  51073. }
  51074. if (!found) {
  51075. var velocitySquaredLength = this._velocity.lengthSquared();
  51076. var a = velocitySquaredLength;
  51077. this._basePoint.subtractToRef(p1, this._tempVector);
  51078. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51079. var c = this._tempVector.lengthSquared() - 1.0;
  51080. var lowestRoot = getLowestRoot(a, b, c, t);
  51081. if (lowestRoot.found) {
  51082. t = lowestRoot.root;
  51083. found = true;
  51084. this._collisionPoint.copyFrom(p1);
  51085. }
  51086. this._basePoint.subtractToRef(p2, this._tempVector);
  51087. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51088. c = this._tempVector.lengthSquared() - 1.0;
  51089. lowestRoot = getLowestRoot(a, b, c, t);
  51090. if (lowestRoot.found) {
  51091. t = lowestRoot.root;
  51092. found = true;
  51093. this._collisionPoint.copyFrom(p2);
  51094. }
  51095. this._basePoint.subtractToRef(p3, this._tempVector);
  51096. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  51097. c = this._tempVector.lengthSquared() - 1.0;
  51098. lowestRoot = getLowestRoot(a, b, c, t);
  51099. if (lowestRoot.found) {
  51100. t = lowestRoot.root;
  51101. found = true;
  51102. this._collisionPoint.copyFrom(p3);
  51103. }
  51104. p2.subtractToRef(p1, this._edge);
  51105. p1.subtractToRef(this._basePoint, this._baseToVertex);
  51106. var edgeSquaredLength = this._edge.lengthSquared();
  51107. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51108. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51109. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51110. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51111. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51112. lowestRoot = getLowestRoot(a, b, c, t);
  51113. if (lowestRoot.found) {
  51114. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51115. if (f >= 0.0 && f <= 1.0) {
  51116. t = lowestRoot.root;
  51117. found = true;
  51118. this._edge.scaleInPlace(f);
  51119. p1.addToRef(this._edge, this._collisionPoint);
  51120. }
  51121. }
  51122. p3.subtractToRef(p2, this._edge);
  51123. p2.subtractToRef(this._basePoint, this._baseToVertex);
  51124. edgeSquaredLength = this._edge.lengthSquared();
  51125. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51126. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51127. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51128. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51129. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51130. lowestRoot = getLowestRoot(a, b, c, t);
  51131. if (lowestRoot.found) {
  51132. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51133. if (f >= 0.0 && f <= 1.0) {
  51134. t = lowestRoot.root;
  51135. found = true;
  51136. this._edge.scaleInPlace(f);
  51137. p2.addToRef(this._edge, this._collisionPoint);
  51138. }
  51139. }
  51140. p1.subtractToRef(p3, this._edge);
  51141. p3.subtractToRef(this._basePoint, this._baseToVertex);
  51142. edgeSquaredLength = this._edge.lengthSquared();
  51143. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  51144. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  51145. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  51146. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  51147. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  51148. lowestRoot = getLowestRoot(a, b, c, t);
  51149. if (lowestRoot.found) {
  51150. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  51151. if (f >= 0.0 && f <= 1.0) {
  51152. t = lowestRoot.root;
  51153. found = true;
  51154. this._edge.scaleInPlace(f);
  51155. p3.addToRef(this._edge, this._collisionPoint);
  51156. }
  51157. }
  51158. }
  51159. if (found) {
  51160. var distToCollision = t * this._velocity.length();
  51161. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  51162. if (!this.intersectionPoint) {
  51163. this.intersectionPoint = this._collisionPoint.clone();
  51164. }
  51165. else {
  51166. this.intersectionPoint.copyFrom(this._collisionPoint);
  51167. }
  51168. this._nearestDistance = distToCollision;
  51169. this.collisionFound = true;
  51170. }
  51171. }
  51172. };
  51173. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  51174. for (var i = indexStart; i < indexEnd; i += 3) {
  51175. var p1 = pts[indices[i] - decal];
  51176. var p2 = pts[indices[i + 1] - decal];
  51177. var p3 = pts[indices[i + 2] - decal];
  51178. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  51179. }
  51180. };
  51181. Collider.prototype._getResponse = function (pos, vel) {
  51182. pos.addToRef(vel, this._destinationPoint);
  51183. vel.scaleInPlace((this._nearestDistance / vel.length()));
  51184. this._basePoint.addToRef(vel, pos);
  51185. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  51186. this._slidePlaneNormal.normalize();
  51187. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  51188. pos.addInPlace(this._displacementVector);
  51189. this.intersectionPoint.addInPlace(this._displacementVector);
  51190. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  51191. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  51192. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  51193. };
  51194. return Collider;
  51195. }());
  51196. BABYLON.Collider = Collider;
  51197. })(BABYLON || (BABYLON = {}));
  51198. //# sourceMappingURL=babylon.collider.js.map
  51199. "use strict";
  51200. var BABYLON;
  51201. (function (BABYLON) {
  51202. //WebWorker code will be inserted to this variable.
  51203. BABYLON.CollisionWorker = "";
  51204. var WorkerTaskType;
  51205. (function (WorkerTaskType) {
  51206. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  51207. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  51208. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  51209. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  51210. var WorkerReplyType;
  51211. (function (WorkerReplyType) {
  51212. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  51213. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  51214. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  51215. var CollisionCoordinatorWorker = /** @class */ (function () {
  51216. function CollisionCoordinatorWorker() {
  51217. var _this = this;
  51218. this._scaledPosition = BABYLON.Vector3.Zero();
  51219. this._scaledVelocity = BABYLON.Vector3.Zero();
  51220. this.onMeshUpdated = function (transformNode) {
  51221. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  51222. };
  51223. this.onGeometryUpdated = function (geometry) {
  51224. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51225. };
  51226. this._afterRender = function () {
  51227. if (!_this._init)
  51228. return;
  51229. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51230. return;
  51231. }
  51232. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51233. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51234. if (_this._runningUpdated > 4) {
  51235. return;
  51236. }
  51237. ++_this._runningUpdated;
  51238. var payload = {
  51239. updatedMeshes: _this._addUpdateMeshesList,
  51240. updatedGeometries: _this._addUpdateGeometriesList,
  51241. removedGeometries: _this._toRemoveGeometryArray,
  51242. removedMeshes: _this._toRemoveMeshesArray
  51243. };
  51244. var message = {
  51245. payload: payload,
  51246. taskType: WorkerTaskType.UPDATE
  51247. };
  51248. var serializable = [];
  51249. for (var id in payload.updatedGeometries) {
  51250. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51251. //prepare transferables
  51252. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51253. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51254. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51255. }
  51256. }
  51257. _this._worker.postMessage(message, serializable);
  51258. _this._addUpdateMeshesList = {};
  51259. _this._addUpdateGeometriesList = {};
  51260. _this._toRemoveGeometryArray = [];
  51261. _this._toRemoveMeshesArray = [];
  51262. };
  51263. this._onMessageFromWorker = function (e) {
  51264. var returnData = e.data;
  51265. if (returnData.error != WorkerReplyType.SUCCESS) {
  51266. //TODO what errors can be returned from the worker?
  51267. BABYLON.Tools.Warn("error returned from worker!");
  51268. return;
  51269. }
  51270. switch (returnData.taskType) {
  51271. case WorkerTaskType.INIT:
  51272. _this._init = true;
  51273. //Update the worked with ALL of the scene's current state
  51274. _this._scene.meshes.forEach(function (mesh) {
  51275. _this.onMeshAdded(mesh);
  51276. });
  51277. _this._scene.getGeometries().forEach(function (geometry) {
  51278. _this.onGeometryAdded(geometry);
  51279. });
  51280. break;
  51281. case WorkerTaskType.UPDATE:
  51282. _this._runningUpdated--;
  51283. break;
  51284. case WorkerTaskType.COLLIDE:
  51285. var returnPayload = returnData.payload;
  51286. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51287. return;
  51288. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51289. if (callback) {
  51290. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51291. if (mesh) {
  51292. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51293. }
  51294. }
  51295. //cleanup
  51296. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51297. break;
  51298. }
  51299. };
  51300. this._collisionsCallbackArray = [];
  51301. this._init = false;
  51302. this._runningUpdated = 0;
  51303. this._addUpdateMeshesList = {};
  51304. this._addUpdateGeometriesList = {};
  51305. this._toRemoveGeometryArray = [];
  51306. this._toRemoveMeshesArray = [];
  51307. }
  51308. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51309. if (!this._init)
  51310. return;
  51311. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51312. return;
  51313. position.divideToRef(collider._radius, this._scaledPosition);
  51314. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51315. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51316. var payload = {
  51317. collider: {
  51318. position: this._scaledPosition.asArray(),
  51319. velocity: this._scaledVelocity.asArray(),
  51320. radius: collider._radius.asArray()
  51321. },
  51322. collisionId: collisionIndex,
  51323. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51324. maximumRetry: maximumRetry
  51325. };
  51326. var message = {
  51327. payload: payload,
  51328. taskType: WorkerTaskType.COLLIDE
  51329. };
  51330. this._worker.postMessage(message);
  51331. };
  51332. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51333. this._scene = scene;
  51334. this._scene.registerAfterRender(this._afterRender);
  51335. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51336. this._worker = new Worker(workerUrl);
  51337. this._worker.onmessage = this._onMessageFromWorker;
  51338. var message = {
  51339. payload: {},
  51340. taskType: WorkerTaskType.INIT
  51341. };
  51342. this._worker.postMessage(message);
  51343. };
  51344. CollisionCoordinatorWorker.prototype.destroy = function () {
  51345. this._scene.unregisterAfterRender(this._afterRender);
  51346. this._worker.terminate();
  51347. };
  51348. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51349. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51350. this.onMeshUpdated(mesh);
  51351. };
  51352. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51353. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51354. };
  51355. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51356. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51357. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51358. this.onGeometryUpdated(geometry);
  51359. };
  51360. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51361. this._toRemoveGeometryArray.push(geometry.id);
  51362. };
  51363. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51364. var submeshes = [];
  51365. if (mesh.subMeshes) {
  51366. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51367. var boundingInfo = sm.getBoundingInfo();
  51368. return {
  51369. position: idx,
  51370. verticesStart: sm.verticesStart,
  51371. verticesCount: sm.verticesCount,
  51372. indexStart: sm.indexStart,
  51373. indexCount: sm.indexCount,
  51374. hasMaterial: !!sm.getMaterial(),
  51375. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51376. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51377. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51378. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51379. };
  51380. });
  51381. }
  51382. var geometryId = null;
  51383. if (mesh instanceof BABYLON.Mesh) {
  51384. var geometry = mesh.geometry;
  51385. geometryId = geometry ? geometry.id : null;
  51386. }
  51387. else if (mesh instanceof BABYLON.InstancedMesh) {
  51388. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51389. geometryId = geometry ? geometry.id : null;
  51390. }
  51391. var boundingInfo = mesh.getBoundingInfo();
  51392. return {
  51393. uniqueId: mesh.uniqueId,
  51394. id: mesh.id,
  51395. name: mesh.name,
  51396. geometryId: geometryId,
  51397. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51398. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51399. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51400. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51401. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51402. subMeshes: submeshes,
  51403. checkCollisions: mesh.checkCollisions
  51404. };
  51405. };
  51406. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51407. return {
  51408. id: geometry.id,
  51409. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51410. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51411. indices: new Uint32Array(geometry.getIndices() || []),
  51412. };
  51413. };
  51414. return CollisionCoordinatorWorker;
  51415. }());
  51416. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51417. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51418. function CollisionCoordinatorLegacy() {
  51419. this._scaledPosition = BABYLON.Vector3.Zero();
  51420. this._scaledVelocity = BABYLON.Vector3.Zero();
  51421. this._finalPosition = BABYLON.Vector3.Zero();
  51422. }
  51423. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51424. position.divideToRef(collider._radius, this._scaledPosition);
  51425. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51426. collider.collidedMesh = null;
  51427. collider._retry = 0;
  51428. collider._initialVelocity = this._scaledVelocity;
  51429. collider._initialPosition = this._scaledPosition;
  51430. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51431. this._finalPosition.multiplyInPlace(collider._radius);
  51432. //run the callback
  51433. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51434. };
  51435. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51436. this._scene = scene;
  51437. };
  51438. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51439. //Legacy need no destruction method.
  51440. };
  51441. //No update in legacy mode
  51442. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51443. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51444. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51445. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51446. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51447. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51448. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51449. if (excludedMesh === void 0) { excludedMesh = null; }
  51450. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51451. if (collider._retry >= maximumRetry) {
  51452. finalPosition.copyFrom(position);
  51453. return;
  51454. }
  51455. // Check if this is a mesh else camera or -1
  51456. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51457. collider._initialize(position, velocity, closeDistance);
  51458. // Check all meshes
  51459. for (var index = 0; index < this._scene.meshes.length; index++) {
  51460. var mesh = this._scene.meshes[index];
  51461. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51462. mesh._checkCollision(collider);
  51463. }
  51464. }
  51465. if (!collider.collisionFound) {
  51466. position.addToRef(velocity, finalPosition);
  51467. return;
  51468. }
  51469. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51470. collider._getResponse(position, velocity);
  51471. }
  51472. if (velocity.length() <= closeDistance) {
  51473. finalPosition.copyFrom(position);
  51474. return;
  51475. }
  51476. collider._retry++;
  51477. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51478. };
  51479. return CollisionCoordinatorLegacy;
  51480. }());
  51481. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51482. })(BABYLON || (BABYLON = {}));
  51483. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51484. "use strict";
  51485. var BABYLON;
  51486. (function (BABYLON) {
  51487. /**
  51488. * A particle represents one of the element emitted by a particle system.
  51489. * This is mainly define by its coordinates, direction, velocity and age.
  51490. */
  51491. var Particle = /** @class */ (function () {
  51492. /**
  51493. * Creates a new instance Particle
  51494. * @param particleSystem the particle system the particle belongs to
  51495. */
  51496. function Particle(
  51497. /**
  51498. * particleSystem the particle system the particle belongs to.
  51499. */
  51500. particleSystem) {
  51501. this.particleSystem = particleSystem;
  51502. /**
  51503. * The world position of the particle in the scene.
  51504. */
  51505. this.position = BABYLON.Vector3.Zero();
  51506. /**
  51507. * The world direction of the particle in the scene.
  51508. */
  51509. this.direction = BABYLON.Vector3.Zero();
  51510. /**
  51511. * The color of the particle.
  51512. */
  51513. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51514. /**
  51515. * The color change of the particle per step.
  51516. */
  51517. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51518. /**
  51519. * Defines how long will the life of the particle be.
  51520. */
  51521. this.lifeTime = 1.0;
  51522. /**
  51523. * The current age of the particle.
  51524. */
  51525. this.age = 0;
  51526. /**
  51527. * The current size of the particle.
  51528. */
  51529. this.size = 0;
  51530. /**
  51531. * The current angle of the particle.
  51532. */
  51533. this.angle = 0;
  51534. /**
  51535. * Defines how fast is the angle changing.
  51536. */
  51537. this.angularSpeed = 0;
  51538. /**
  51539. * Defines the cell index used by the particle to be rendered from a sprite.
  51540. */
  51541. this.cellIndex = 0;
  51542. this._currentFrameCounter = 0;
  51543. if (!this.particleSystem.isAnimationSheetEnabled) {
  51544. return;
  51545. }
  51546. this.updateCellInfoFromSystem();
  51547. }
  51548. Particle.prototype.updateCellInfoFromSystem = function () {
  51549. this.cellIndex = this.particleSystem.startSpriteCellID;
  51550. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51551. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51552. }
  51553. else {
  51554. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51555. }
  51556. };
  51557. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51558. // (ageOffset / scaledUpdateSpeed) / available cells
  51559. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51560. this._currentFrameCounter += scaledUpdateSpeed;
  51561. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51562. this._currentFrameCounter = 0;
  51563. this.cellIndex++;
  51564. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51565. this.cellIndex = this.particleSystem.endSpriteCellID;
  51566. }
  51567. }
  51568. };
  51569. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51570. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51571. this.cellIndex++;
  51572. this._currentFrameCounter = 0;
  51573. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51574. if (this.particleSystem.spriteCellLoop) {
  51575. this.cellIndex = this.particleSystem.startSpriteCellID;
  51576. }
  51577. else {
  51578. this.cellIndex = this.particleSystem.endSpriteCellID;
  51579. }
  51580. }
  51581. }
  51582. else {
  51583. this._currentFrameCounter++;
  51584. }
  51585. };
  51586. /**
  51587. * Copy the properties of particle to another one.
  51588. * @param other the particle to copy the information to.
  51589. */
  51590. Particle.prototype.copyTo = function (other) {
  51591. other.position.copyFrom(this.position);
  51592. other.direction.copyFrom(this.direction);
  51593. other.color.copyFrom(this.color);
  51594. other.colorStep.copyFrom(this.colorStep);
  51595. other.lifeTime = this.lifeTime;
  51596. other.age = this.age;
  51597. other.size = this.size;
  51598. other.angle = this.angle;
  51599. other.angularSpeed = this.angularSpeed;
  51600. other.particleSystem = this.particleSystem;
  51601. other.cellIndex = this.cellIndex;
  51602. };
  51603. return Particle;
  51604. }());
  51605. BABYLON.Particle = Particle;
  51606. })(BABYLON || (BABYLON = {}));
  51607. //# sourceMappingURL=babylon.particle.js.map
  51608. "use strict";
  51609. var BABYLON;
  51610. (function (BABYLON) {
  51611. /**
  51612. * This represents a particle system in Babylon.
  51613. * 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.
  51614. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51615. * @example https://doc.babylonjs.com/babylon101/particles
  51616. */
  51617. var ParticleSystem = /** @class */ (function () {
  51618. /**
  51619. * Instantiates a particle system.
  51620. * 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.
  51621. * @param name The name of the particle system
  51622. * @param capacity The max number of particles alive at the same time
  51623. * @param scene The scene the particle system belongs to
  51624. * @param customEffect a custom effect used to change the way particles are rendered by default
  51625. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51626. * @param epsilon Offset used to render the particles
  51627. */
  51628. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51629. if (customEffect === void 0) { customEffect = null; }
  51630. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51631. if (epsilon === void 0) { epsilon = 0.01; }
  51632. var _this = this;
  51633. /**
  51634. * List of animations used by the particle system.
  51635. */
  51636. this.animations = [];
  51637. /**
  51638. * The rendering group used by the Particle system to chose when to render.
  51639. */
  51640. this.renderingGroupId = 0;
  51641. /**
  51642. * The emitter represents the Mesh or position we are attaching the particle system to.
  51643. */
  51644. this.emitter = null;
  51645. /**
  51646. * The maximum number of particles to emit per frame
  51647. */
  51648. this.emitRate = 10;
  51649. /**
  51650. * If you want to launch only a few particles at once, that can be done, as well.
  51651. */
  51652. this.manualEmitCount = -1;
  51653. /**
  51654. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51655. */
  51656. this.updateSpeed = 0.01;
  51657. /**
  51658. * The amount of time the particle system is running (depends of the overall update speed).
  51659. */
  51660. this.targetStopDuration = 0;
  51661. /**
  51662. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51663. */
  51664. this.disposeOnStop = false;
  51665. /**
  51666. * Minimum power of emitting particles.
  51667. */
  51668. this.minEmitPower = 1;
  51669. /**
  51670. * Maximum power of emitting particles.
  51671. */
  51672. this.maxEmitPower = 1;
  51673. /**
  51674. * Minimum life time of emitting particles.
  51675. */
  51676. this.minLifeTime = 1;
  51677. /**
  51678. * Maximum life time of emitting particles.
  51679. */
  51680. this.maxLifeTime = 1;
  51681. /**
  51682. * Minimum Size of emitting particles.
  51683. */
  51684. this.minSize = 1;
  51685. /**
  51686. * Maximum Size of emitting particles.
  51687. */
  51688. this.maxSize = 1;
  51689. /**
  51690. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51691. */
  51692. this.minAngularSpeed = 0;
  51693. /**
  51694. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51695. */
  51696. this.maxAngularSpeed = 0;
  51697. /**
  51698. * The layer mask we are rendering the particles through.
  51699. */
  51700. this.layerMask = 0x0FFFFFFF;
  51701. /**
  51702. * This can help using your own shader to render the particle system.
  51703. * The according effect will be created
  51704. */
  51705. this.customShader = null;
  51706. /**
  51707. * By default particle system starts as soon as they are created. This prevents the
  51708. * automatic start to happen and let you decide when to start emitting particles.
  51709. */
  51710. this.preventAutoStart = false;
  51711. /**
  51712. * Callback triggered when the particle animation is ending.
  51713. */
  51714. this.onAnimationEnd = null;
  51715. /**
  51716. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51717. */
  51718. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51719. /**
  51720. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51721. * to override the particles.
  51722. */
  51723. this.forceDepthWrite = false;
  51724. /**
  51725. * You can use gravity if you want to give an orientation to your particles.
  51726. */
  51727. this.gravity = BABYLON.Vector3.Zero();
  51728. /**
  51729. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51730. */
  51731. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51732. /**
  51733. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51734. */
  51735. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51736. /**
  51737. * Color the particle will have at the end of its lifetime.
  51738. */
  51739. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51740. /**
  51741. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51742. */
  51743. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51744. /**
  51745. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51746. */
  51747. this.spriteCellLoop = true;
  51748. /**
  51749. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51750. */
  51751. this.spriteCellChangeSpeed = 0;
  51752. /**
  51753. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51754. */
  51755. this.startSpriteCellID = 0;
  51756. /**
  51757. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51758. */
  51759. this.endSpriteCellID = 0;
  51760. /**
  51761. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51762. */
  51763. this.spriteCellWidth = 0;
  51764. /**
  51765. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51766. */
  51767. this.spriteCellHeight = 0;
  51768. /**
  51769. * An event triggered when the system is disposed.
  51770. */
  51771. this.onDisposeObservable = new BABYLON.Observable();
  51772. this._particles = new Array();
  51773. this._stockParticles = new Array();
  51774. this._newPartsExcess = 0;
  51775. this._vertexBuffers = {};
  51776. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51777. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51778. this._scaledDirection = BABYLON.Vector3.Zero();
  51779. this._scaledGravity = BABYLON.Vector3.Zero();
  51780. this._currentRenderId = -1;
  51781. this._started = false;
  51782. this._stopped = false;
  51783. this._actualFrame = 0;
  51784. this._vertexBufferSize = 11;
  51785. // start of sub system methods
  51786. /**
  51787. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51788. * Its lifetime will start back at 0.
  51789. */
  51790. this.recycleParticle = function (particle) {
  51791. var lastParticle = _this._particles.pop();
  51792. if (lastParticle !== particle) {
  51793. lastParticle.copyTo(particle);
  51794. }
  51795. _this._stockParticles.push(lastParticle);
  51796. };
  51797. this._createParticle = function () {
  51798. var particle;
  51799. if (_this._stockParticles.length !== 0) {
  51800. particle = _this._stockParticles.pop();
  51801. particle.age = 0;
  51802. particle.cellIndex = _this.startSpriteCellID;
  51803. }
  51804. else {
  51805. particle = new BABYLON.Particle(_this);
  51806. }
  51807. return particle;
  51808. };
  51809. this._emitFromParticle = function (particle) {
  51810. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51811. return;
  51812. }
  51813. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51814. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51815. subSystem._rootParticleSystem = _this;
  51816. _this.activeSubSystems.push(subSystem);
  51817. subSystem.start();
  51818. };
  51819. this._appendParticleVertexes = null;
  51820. this.id = name;
  51821. this.name = name;
  51822. this._capacity = capacity;
  51823. this._epsilon = epsilon;
  51824. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51825. if (isAnimationSheetEnabled) {
  51826. this._vertexBufferSize = 12;
  51827. }
  51828. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51829. this._customEffect = customEffect;
  51830. scene.particleSystems.push(this);
  51831. this._createIndexBuffer();
  51832. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51833. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51834. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51835. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51836. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51837. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51838. if (this._isAnimationSheetEnabled) {
  51839. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51840. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51841. }
  51842. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51843. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51844. this._vertexBuffers["options"] = options;
  51845. // Default emitter type
  51846. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51847. this.updateFunction = function (particles) {
  51848. for (var index = 0; index < particles.length; index++) {
  51849. var particle = particles[index];
  51850. particle.age += _this._scaledUpdateSpeed;
  51851. if (particle.age >= particle.lifeTime) {
  51852. _this._emitFromParticle(particle);
  51853. _this.recycleParticle(particle);
  51854. index--;
  51855. continue;
  51856. }
  51857. else {
  51858. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51859. particle.color.addInPlace(_this._scaledColorStep);
  51860. if (particle.color.a < 0)
  51861. particle.color.a = 0;
  51862. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51863. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51864. particle.position.addInPlace(_this._scaledDirection);
  51865. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51866. particle.direction.addInPlace(_this._scaledGravity);
  51867. if (_this._isAnimationSheetEnabled) {
  51868. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51869. }
  51870. }
  51871. }
  51872. };
  51873. }
  51874. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51875. /**
  51876. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51877. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51878. */
  51879. get: function () {
  51880. if (this.particleEmitterType.direction1) {
  51881. return this.particleEmitterType.direction1;
  51882. }
  51883. return BABYLON.Vector3.Zero();
  51884. },
  51885. set: function (value) {
  51886. if (this.particleEmitterType.direction1) {
  51887. this.particleEmitterType.direction1 = value;
  51888. }
  51889. },
  51890. enumerable: true,
  51891. configurable: true
  51892. });
  51893. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51894. /**
  51895. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51896. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51897. */
  51898. get: function () {
  51899. if (this.particleEmitterType.direction2) {
  51900. return this.particleEmitterType.direction2;
  51901. }
  51902. return BABYLON.Vector3.Zero();
  51903. },
  51904. set: function (value) {
  51905. if (this.particleEmitterType.direction2) {
  51906. this.particleEmitterType.direction2 = value;
  51907. }
  51908. },
  51909. enumerable: true,
  51910. configurable: true
  51911. });
  51912. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51913. /**
  51914. * 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.
  51915. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51916. */
  51917. get: function () {
  51918. if (this.particleEmitterType.minEmitBox) {
  51919. return this.particleEmitterType.minEmitBox;
  51920. }
  51921. return BABYLON.Vector3.Zero();
  51922. },
  51923. set: function (value) {
  51924. if (this.particleEmitterType.minEmitBox) {
  51925. this.particleEmitterType.minEmitBox = value;
  51926. }
  51927. },
  51928. enumerable: true,
  51929. configurable: true
  51930. });
  51931. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51932. /**
  51933. * 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.
  51934. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51935. */
  51936. get: function () {
  51937. if (this.particleEmitterType.maxEmitBox) {
  51938. return this.particleEmitterType.maxEmitBox;
  51939. }
  51940. return BABYLON.Vector3.Zero();
  51941. },
  51942. set: function (value) {
  51943. if (this.particleEmitterType.maxEmitBox) {
  51944. this.particleEmitterType.maxEmitBox = value;
  51945. }
  51946. },
  51947. enumerable: true,
  51948. configurable: true
  51949. });
  51950. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51951. /**
  51952. * Sets a callback that will be triggered when the system is disposed.
  51953. */
  51954. set: function (callback) {
  51955. if (this._onDisposeObserver) {
  51956. this.onDisposeObservable.remove(this._onDisposeObserver);
  51957. }
  51958. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51959. },
  51960. enumerable: true,
  51961. configurable: true
  51962. });
  51963. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51964. /**
  51965. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51966. */
  51967. get: function () {
  51968. return this._isAnimationSheetEnabled;
  51969. },
  51970. enumerable: true,
  51971. configurable: true
  51972. });
  51973. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51974. //end of Sub-emitter
  51975. /**
  51976. * Gets the current list of active particles
  51977. */
  51978. get: function () {
  51979. return this._particles;
  51980. },
  51981. enumerable: true,
  51982. configurable: true
  51983. });
  51984. /**
  51985. * Returns the string "ParticleSystem"
  51986. * @returns a string containing the class name
  51987. */
  51988. ParticleSystem.prototype.getClassName = function () {
  51989. return "ParticleSystem";
  51990. };
  51991. ParticleSystem.prototype._createIndexBuffer = function () {
  51992. var indices = [];
  51993. var index = 0;
  51994. for (var count = 0; count < this._capacity; count++) {
  51995. indices.push(index);
  51996. indices.push(index + 1);
  51997. indices.push(index + 2);
  51998. indices.push(index);
  51999. indices.push(index + 2);
  52000. indices.push(index + 3);
  52001. index += 4;
  52002. }
  52003. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  52004. };
  52005. /**
  52006. * Gets the maximum number of particles active at the same time.
  52007. * @returns The max number of active particles.
  52008. */
  52009. ParticleSystem.prototype.getCapacity = function () {
  52010. return this._capacity;
  52011. };
  52012. /**
  52013. * Gets Wether there are still active particles in the system.
  52014. * @returns True if it is alive, otherwise false.
  52015. */
  52016. ParticleSystem.prototype.isAlive = function () {
  52017. return this._alive;
  52018. };
  52019. /**
  52020. * Gets Wether the system has been started.
  52021. * @returns True if it has been started, otherwise false.
  52022. */
  52023. ParticleSystem.prototype.isStarted = function () {
  52024. return this._started;
  52025. };
  52026. /**
  52027. * Starts the particle system and begins to emit.
  52028. */
  52029. ParticleSystem.prototype.start = function () {
  52030. this._started = true;
  52031. this._stopped = false;
  52032. this._actualFrame = 0;
  52033. if (this.subEmitters && this.subEmitters.length != 0) {
  52034. this.activeSubSystems = new Array();
  52035. }
  52036. };
  52037. /**
  52038. * Stops the particle system.
  52039. * @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.
  52040. */
  52041. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  52042. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  52043. this._stopped = true;
  52044. if (stopSubEmitters) {
  52045. this._stopSubEmitters();
  52046. }
  52047. };
  52048. // animation sheet
  52049. /**
  52050. * Remove all active particles
  52051. */
  52052. ParticleSystem.prototype.reset = function () {
  52053. this._stockParticles = [];
  52054. this._particles = [];
  52055. };
  52056. /**
  52057. * @ignore (for internal use only)
  52058. */
  52059. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  52060. var offset = index * this._vertexBufferSize;
  52061. this._vertexData[offset] = particle.position.x;
  52062. this._vertexData[offset + 1] = particle.position.y;
  52063. this._vertexData[offset + 2] = particle.position.z;
  52064. this._vertexData[offset + 3] = particle.color.r;
  52065. this._vertexData[offset + 4] = particle.color.g;
  52066. this._vertexData[offset + 5] = particle.color.b;
  52067. this._vertexData[offset + 6] = particle.color.a;
  52068. this._vertexData[offset + 7] = particle.angle;
  52069. this._vertexData[offset + 8] = particle.size;
  52070. this._vertexData[offset + 9] = offsetX;
  52071. this._vertexData[offset + 10] = offsetY;
  52072. };
  52073. /**
  52074. * @ignore (for internal use only)
  52075. */
  52076. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  52077. if (offsetX === 0)
  52078. offsetX = this._epsilon;
  52079. else if (offsetX === 1)
  52080. offsetX = 1 - this._epsilon;
  52081. if (offsetY === 0)
  52082. offsetY = this._epsilon;
  52083. else if (offsetY === 1)
  52084. offsetY = 1 - this._epsilon;
  52085. var offset = index * this._vertexBufferSize;
  52086. this._vertexData[offset] = particle.position.x;
  52087. this._vertexData[offset + 1] = particle.position.y;
  52088. this._vertexData[offset + 2] = particle.position.z;
  52089. this._vertexData[offset + 3] = particle.color.r;
  52090. this._vertexData[offset + 4] = particle.color.g;
  52091. this._vertexData[offset + 5] = particle.color.b;
  52092. this._vertexData[offset + 6] = particle.color.a;
  52093. this._vertexData[offset + 7] = particle.angle;
  52094. this._vertexData[offset + 8] = particle.size;
  52095. this._vertexData[offset + 9] = offsetX;
  52096. this._vertexData[offset + 10] = offsetY;
  52097. this._vertexData[offset + 11] = particle.cellIndex;
  52098. };
  52099. ParticleSystem.prototype._stopSubEmitters = function () {
  52100. if (!this.activeSubSystems) {
  52101. return;
  52102. }
  52103. this.activeSubSystems.forEach(function (subSystem) {
  52104. subSystem.stop(true);
  52105. });
  52106. this.activeSubSystems = new Array();
  52107. };
  52108. ParticleSystem.prototype._removeFromRoot = function () {
  52109. if (!this._rootParticleSystem) {
  52110. return;
  52111. }
  52112. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  52113. if (index !== -1) {
  52114. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  52115. }
  52116. };
  52117. // end of sub system methods
  52118. ParticleSystem.prototype._update = function (newParticles) {
  52119. // Update current
  52120. this._alive = this._particles.length > 0;
  52121. this.updateFunction(this._particles);
  52122. // Add new ones
  52123. var worldMatrix;
  52124. if (this.emitter.position) {
  52125. var emitterMesh = this.emitter;
  52126. worldMatrix = emitterMesh.getWorldMatrix();
  52127. }
  52128. else {
  52129. var emitterPosition = this.emitter;
  52130. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  52131. }
  52132. var particle;
  52133. for (var index = 0; index < newParticles; index++) {
  52134. if (this._particles.length === this._capacity) {
  52135. break;
  52136. }
  52137. particle = this._createParticle();
  52138. this._particles.push(particle);
  52139. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  52140. if (this.startPositionFunction) {
  52141. this.startPositionFunction(worldMatrix, particle.position, particle);
  52142. }
  52143. else {
  52144. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  52145. }
  52146. if (this.startDirectionFunction) {
  52147. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52148. }
  52149. else {
  52150. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  52151. }
  52152. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  52153. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  52154. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  52155. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  52156. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  52157. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  52158. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  52159. }
  52160. };
  52161. ParticleSystem.prototype._getEffect = function () {
  52162. if (this._customEffect) {
  52163. return this._customEffect;
  52164. }
  52165. ;
  52166. var defines = [];
  52167. if (this._scene.clipPlane) {
  52168. defines.push("#define CLIPPLANE");
  52169. }
  52170. if (this._isAnimationSheetEnabled) {
  52171. defines.push("#define ANIMATESHEET");
  52172. }
  52173. // Effect
  52174. var join = defines.join("\n");
  52175. if (this._cachedDefines !== join) {
  52176. this._cachedDefines = join;
  52177. var attributesNamesOrOptions;
  52178. var effectCreationOption;
  52179. if (this._isAnimationSheetEnabled) {
  52180. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  52181. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  52182. }
  52183. else {
  52184. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  52185. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  52186. }
  52187. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  52188. }
  52189. return this._effect;
  52190. };
  52191. /**
  52192. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  52193. */
  52194. ParticleSystem.prototype.animate = function () {
  52195. if (!this._started)
  52196. return;
  52197. var effect = this._getEffect();
  52198. // Check
  52199. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  52200. return;
  52201. if (this._currentRenderId === this._scene.getRenderId()) {
  52202. return;
  52203. }
  52204. this._currentRenderId = this._scene.getRenderId();
  52205. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  52206. // determine the number of particles we need to create
  52207. var newParticles;
  52208. if (this.manualEmitCount > -1) {
  52209. newParticles = this.manualEmitCount;
  52210. this._newPartsExcess = 0;
  52211. this.manualEmitCount = 0;
  52212. }
  52213. else {
  52214. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  52215. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  52216. }
  52217. if (this._newPartsExcess > 1.0) {
  52218. newParticles += this._newPartsExcess >> 0;
  52219. this._newPartsExcess -= this._newPartsExcess >> 0;
  52220. }
  52221. this._alive = false;
  52222. if (!this._stopped) {
  52223. this._actualFrame += this._scaledUpdateSpeed;
  52224. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52225. this.stop();
  52226. }
  52227. else {
  52228. newParticles = 0;
  52229. }
  52230. this._update(newParticles);
  52231. // Stopped?
  52232. if (this._stopped) {
  52233. if (!this._alive) {
  52234. this._started = false;
  52235. if (this.onAnimationEnd) {
  52236. this.onAnimationEnd();
  52237. }
  52238. if (this.disposeOnStop) {
  52239. this._scene._toBeDisposed.push(this);
  52240. }
  52241. }
  52242. }
  52243. // Animation sheet
  52244. if (this._isAnimationSheetEnabled) {
  52245. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52246. }
  52247. else {
  52248. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52249. }
  52250. // Update VBO
  52251. var offset = 0;
  52252. for (var index = 0; index < this._particles.length; index++) {
  52253. var particle = this._particles[index];
  52254. this._appendParticleVertexes(offset, particle);
  52255. offset += 4;
  52256. }
  52257. if (this._vertexBuffer) {
  52258. this._vertexBuffer.update(this._vertexData);
  52259. }
  52260. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52261. this.stop();
  52262. }
  52263. };
  52264. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52265. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52266. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52267. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52268. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52269. };
  52270. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52271. this._appendParticleVertex(offset++, particle, 0, 0);
  52272. this._appendParticleVertex(offset++, particle, 1, 0);
  52273. this._appendParticleVertex(offset++, particle, 1, 1);
  52274. this._appendParticleVertex(offset++, particle, 0, 1);
  52275. };
  52276. /**
  52277. * Rebuilds the particle system.
  52278. */
  52279. ParticleSystem.prototype.rebuild = function () {
  52280. this._createIndexBuffer();
  52281. if (this._vertexBuffer) {
  52282. this._vertexBuffer._rebuild();
  52283. }
  52284. };
  52285. /**
  52286. * Is this system ready to be used/rendered
  52287. * @return true if the system is ready
  52288. */
  52289. ParticleSystem.prototype.isReady = function () {
  52290. var effect = this._getEffect();
  52291. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52292. return false;
  52293. }
  52294. return true;
  52295. };
  52296. /**
  52297. * Renders the particle system in its current state.
  52298. * @returns the current number of particles
  52299. */
  52300. ParticleSystem.prototype.render = function () {
  52301. var effect = this._getEffect();
  52302. // Check
  52303. if (!this.isReady() || !this._particles.length) {
  52304. return 0;
  52305. }
  52306. var engine = this._scene.getEngine();
  52307. // Render
  52308. engine.enableEffect(effect);
  52309. engine.setState(false);
  52310. var viewMatrix = this._scene.getViewMatrix();
  52311. effect.setTexture("diffuseSampler", this.particleTexture);
  52312. effect.setMatrix("view", viewMatrix);
  52313. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52314. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52315. var baseSize = this.particleTexture.getBaseSize();
  52316. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52317. }
  52318. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52319. if (this._scene.clipPlane) {
  52320. var clipPlane = this._scene.clipPlane;
  52321. var invView = viewMatrix.clone();
  52322. invView.invert();
  52323. effect.setMatrix("invView", invView);
  52324. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52325. }
  52326. // VBOs
  52327. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52328. // Draw order
  52329. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52330. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52331. }
  52332. else {
  52333. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52334. }
  52335. if (this.forceDepthWrite) {
  52336. engine.setDepthWrite(true);
  52337. }
  52338. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52339. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52340. return this._particles.length;
  52341. };
  52342. /**
  52343. * Disposes the particle system and free the associated resources
  52344. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52345. */
  52346. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52347. if (disposeTexture === void 0) { disposeTexture = true; }
  52348. if (this._vertexBuffer) {
  52349. this._vertexBuffer.dispose();
  52350. this._vertexBuffer = null;
  52351. }
  52352. if (this._indexBuffer) {
  52353. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52354. this._indexBuffer = null;
  52355. }
  52356. if (disposeTexture && this.particleTexture) {
  52357. this.particleTexture.dispose();
  52358. this.particleTexture = null;
  52359. }
  52360. this._removeFromRoot();
  52361. // Remove from scene
  52362. var index = this._scene.particleSystems.indexOf(this);
  52363. if (index > -1) {
  52364. this._scene.particleSystems.splice(index, 1);
  52365. }
  52366. // Callback
  52367. this.onDisposeObservable.notifyObservers(this);
  52368. this.onDisposeObservable.clear();
  52369. };
  52370. /**
  52371. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52372. * @param radius The radius of the sphere to emit from
  52373. * @returns the emitter
  52374. */
  52375. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52376. if (radius === void 0) { radius = 1; }
  52377. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52378. this.particleEmitterType = particleEmitter;
  52379. return particleEmitter;
  52380. };
  52381. /**
  52382. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52383. * @param radius The radius of the sphere to emit from
  52384. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52385. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52386. * @returns the emitter
  52387. */
  52388. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52389. if (radius === void 0) { radius = 1; }
  52390. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52391. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52392. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52393. this.particleEmitterType = particleEmitter;
  52394. return particleEmitter;
  52395. };
  52396. /**
  52397. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52398. * @param radius The radius of the cone to emit from
  52399. * @param angle The base angle of the cone
  52400. * @returns the emitter
  52401. */
  52402. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52403. if (radius === void 0) { radius = 1; }
  52404. if (angle === void 0) { angle = Math.PI / 4; }
  52405. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52406. this.particleEmitterType = particleEmitter;
  52407. return particleEmitter;
  52408. };
  52409. // 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.
  52410. /**
  52411. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52412. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52413. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52414. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52415. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52416. * @returns the emitter
  52417. */
  52418. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52419. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52420. this.particleEmitterType = particleEmitter;
  52421. this.direction1 = direction1;
  52422. this.direction2 = direction2;
  52423. this.minEmitBox = minEmitBox;
  52424. this.maxEmitBox = maxEmitBox;
  52425. return particleEmitter;
  52426. };
  52427. // Clone
  52428. /**
  52429. * Clones the particle system.
  52430. * @param name The name of the cloned object
  52431. * @param newEmitter The new emitter to use
  52432. * @returns the cloned particle system
  52433. */
  52434. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52435. var custom = null;
  52436. var program = null;
  52437. if (this.customShader != null) {
  52438. program = this.customShader;
  52439. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52440. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52441. }
  52442. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52443. result.customShader = program;
  52444. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52445. if (newEmitter === undefined) {
  52446. newEmitter = this.emitter;
  52447. }
  52448. result.emitter = newEmitter;
  52449. if (this.particleTexture) {
  52450. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52451. }
  52452. if (!this.preventAutoStart) {
  52453. result.start();
  52454. }
  52455. return result;
  52456. };
  52457. /**
  52458. * Serializes the particle system to a JSON object.
  52459. * @returns the JSON object
  52460. */
  52461. ParticleSystem.prototype.serialize = function () {
  52462. var serializationObject = {};
  52463. serializationObject.name = this.name;
  52464. serializationObject.id = this.id;
  52465. // Emitter
  52466. if (this.emitter.position) {
  52467. var emitterMesh = this.emitter;
  52468. serializationObject.emitterId = emitterMesh.id;
  52469. }
  52470. else {
  52471. var emitterPosition = this.emitter;
  52472. serializationObject.emitter = emitterPosition.asArray();
  52473. }
  52474. serializationObject.capacity = this.getCapacity();
  52475. if (this.particleTexture) {
  52476. serializationObject.textureName = this.particleTexture.name;
  52477. }
  52478. // Animations
  52479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52480. // Particle system
  52481. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52482. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52483. serializationObject.minSize = this.minSize;
  52484. serializationObject.maxSize = this.maxSize;
  52485. serializationObject.minEmitPower = this.minEmitPower;
  52486. serializationObject.maxEmitPower = this.maxEmitPower;
  52487. serializationObject.minLifeTime = this.minLifeTime;
  52488. serializationObject.maxLifeTime = this.maxLifeTime;
  52489. serializationObject.emitRate = this.emitRate;
  52490. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52491. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52492. serializationObject.gravity = this.gravity.asArray();
  52493. serializationObject.direction1 = this.direction1.asArray();
  52494. serializationObject.direction2 = this.direction2.asArray();
  52495. serializationObject.color1 = this.color1.asArray();
  52496. serializationObject.color2 = this.color2.asArray();
  52497. serializationObject.colorDead = this.colorDead.asArray();
  52498. serializationObject.updateSpeed = this.updateSpeed;
  52499. serializationObject.targetStopDuration = this.targetStopDuration;
  52500. serializationObject.textureMask = this.textureMask.asArray();
  52501. serializationObject.blendMode = this.blendMode;
  52502. serializationObject.customShader = this.customShader;
  52503. serializationObject.preventAutoStart = this.preventAutoStart;
  52504. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52505. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52506. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52507. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52508. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52509. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52510. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52511. // Emitter
  52512. if (this.particleEmitterType) {
  52513. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52514. }
  52515. return serializationObject;
  52516. };
  52517. /**
  52518. * Parses a JSON object to create a particle system.
  52519. * @param parsedParticleSystem The JSON object to parse
  52520. * @param scene The scene to create the particle system in
  52521. * @param rootUrl The root url to use to load external dependencies like texture
  52522. * @returns the Parsed particle system
  52523. */
  52524. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52525. var name = parsedParticleSystem.name;
  52526. var custom = null;
  52527. var program = null;
  52528. if (parsedParticleSystem.customShader) {
  52529. program = parsedParticleSystem.customShader;
  52530. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52531. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52532. }
  52533. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52534. particleSystem.customShader = program;
  52535. if (parsedParticleSystem.id) {
  52536. particleSystem.id = parsedParticleSystem.id;
  52537. }
  52538. // Auto start
  52539. if (parsedParticleSystem.preventAutoStart) {
  52540. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52541. }
  52542. // Texture
  52543. if (parsedParticleSystem.textureName) {
  52544. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52545. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52546. }
  52547. // Emitter
  52548. if (parsedParticleSystem.emitterId) {
  52549. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52550. }
  52551. else {
  52552. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52553. }
  52554. // Animations
  52555. if (parsedParticleSystem.animations) {
  52556. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52557. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52558. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52559. }
  52560. }
  52561. if (parsedParticleSystem.autoAnimate) {
  52562. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52563. }
  52564. // Particle system
  52565. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52566. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52567. particleSystem.minSize = parsedParticleSystem.minSize;
  52568. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52569. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52570. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52571. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52572. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52573. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52574. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52575. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52576. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52577. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52578. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52579. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52580. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52581. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52582. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52583. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52584. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52585. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52586. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52587. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52588. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52589. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52590. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52591. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52592. if (!particleSystem.preventAutoStart) {
  52593. particleSystem.start();
  52594. }
  52595. return particleSystem;
  52596. };
  52597. /**
  52598. * Source color is added to the destination color without alpha affecting the result.
  52599. */
  52600. ParticleSystem.BLENDMODE_ONEONE = 0;
  52601. /**
  52602. * Blend current color and particle color using particle’s alpha.
  52603. */
  52604. ParticleSystem.BLENDMODE_STANDARD = 1;
  52605. return ParticleSystem;
  52606. }());
  52607. BABYLON.ParticleSystem = ParticleSystem;
  52608. })(BABYLON || (BABYLON = {}));
  52609. //# sourceMappingURL=babylon.particleSystem.js.map
  52610. "use strict";
  52611. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52612. "use strict";
  52613. var BABYLON;
  52614. (function (BABYLON) {
  52615. /**
  52616. * Particle emitter emitting particles from the inside of a box.
  52617. * It emits the particles randomly between 2 given directions.
  52618. */
  52619. var BoxParticleEmitter = /** @class */ (function () {
  52620. /**
  52621. * Creates a new instance BoxParticleEmitter
  52622. */
  52623. function BoxParticleEmitter() {
  52624. /**
  52625. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52626. */
  52627. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52628. /**
  52629. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52630. */
  52631. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52632. /**
  52633. * 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.
  52634. */
  52635. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52636. /**
  52637. * 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.
  52638. */
  52639. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52640. }
  52641. /**
  52642. * Called by the particle System when the direction is computed for the created particle.
  52643. * @param emitPower is the power of the particle (speed)
  52644. * @param worldMatrix is the world matrix of the particle system
  52645. * @param directionToUpdate is the direction vector to update with the result
  52646. * @param particle is the particle we are computed the direction for
  52647. */
  52648. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52649. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52650. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52651. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52652. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52653. };
  52654. /**
  52655. * Called by the particle System when the position is computed for the created particle.
  52656. * @param worldMatrix is the world matrix of the particle system
  52657. * @param positionToUpdate is the position vector to update with the result
  52658. * @param particle is the particle we are computed the position for
  52659. */
  52660. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52661. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52662. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52663. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52664. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52665. };
  52666. /**
  52667. * Clones the current emitter and returns a copy of it
  52668. * @returns the new emitter
  52669. */
  52670. BoxParticleEmitter.prototype.clone = function () {
  52671. var newOne = new BoxParticleEmitter();
  52672. BABYLON.Tools.DeepCopy(this, newOne);
  52673. return newOne;
  52674. };
  52675. /**
  52676. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52677. * @param effect defines the update shader
  52678. */
  52679. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52680. effect.setVector3("direction1", this.direction1);
  52681. effect.setVector3("direction2", this.direction2);
  52682. effect.setVector3("minEmitBox", this.minEmitBox);
  52683. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52684. };
  52685. /**
  52686. * Returns a string to use to update the GPU particles update shader
  52687. * @returns a string containng the defines string
  52688. */
  52689. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52690. return "#define BOXEMITTER";
  52691. };
  52692. /**
  52693. * Returns the string "BoxEmitter"
  52694. * @returns a string containing the class name
  52695. */
  52696. BoxParticleEmitter.prototype.getClassName = function () {
  52697. return "BoxEmitter";
  52698. };
  52699. /**
  52700. * Serializes the particle system to a JSON object.
  52701. * @returns the JSON object
  52702. */
  52703. BoxParticleEmitter.prototype.serialize = function () {
  52704. var serializationObject = {};
  52705. serializationObject.type = this.getClassName();
  52706. serializationObject.direction1 = this.direction1.asArray();
  52707. ;
  52708. serializationObject.direction2 = this.direction2.asArray();
  52709. ;
  52710. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52711. ;
  52712. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52713. ;
  52714. return serializationObject;
  52715. };
  52716. /**
  52717. * Parse properties from a JSON object
  52718. * @param serializationObject defines the JSON object
  52719. */
  52720. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52721. this.direction1.copyFrom(serializationObject.direction1);
  52722. this.direction2.copyFrom(serializationObject.direction2);
  52723. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52724. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52725. };
  52726. return BoxParticleEmitter;
  52727. }());
  52728. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52729. })(BABYLON || (BABYLON = {}));
  52730. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52731. "use strict";
  52732. var BABYLON;
  52733. (function (BABYLON) {
  52734. /**
  52735. * Particle emitter emitting particles from the inside of a cone.
  52736. * It emits the particles alongside the cone volume from the base to the particle.
  52737. * The emission direction might be randomized.
  52738. */
  52739. var ConeParticleEmitter = /** @class */ (function () {
  52740. /**
  52741. * Creates a new instance ConeParticleEmitter
  52742. * @param radius the radius of the emission cone (1 by default)
  52743. * @param angles the cone base angle (PI by default)
  52744. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52745. */
  52746. function ConeParticleEmitter(radius,
  52747. /**
  52748. * The radius of the emission cone.
  52749. */
  52750. angle,
  52751. /**
  52752. * The cone base angle.
  52753. */
  52754. directionRandomizer) {
  52755. if (radius === void 0) { radius = 1; }
  52756. if (angle === void 0) { angle = Math.PI; }
  52757. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52758. this.angle = angle;
  52759. this.directionRandomizer = directionRandomizer;
  52760. this.radius = radius;
  52761. }
  52762. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52763. /**
  52764. * Gets the radius of the emission cone.
  52765. */
  52766. get: function () {
  52767. return this._radius;
  52768. },
  52769. /**
  52770. * Sets the radius of the emission cone.
  52771. */
  52772. set: function (value) {
  52773. this._radius = value;
  52774. if (this.angle !== 0) {
  52775. this._height = value / Math.tan(this.angle / 2);
  52776. }
  52777. else {
  52778. this._height = 1;
  52779. }
  52780. },
  52781. enumerable: true,
  52782. configurable: true
  52783. });
  52784. /**
  52785. * Called by the particle System when the direction is computed for the created particle.
  52786. * @param emitPower is the power of the particle (speed)
  52787. * @param worldMatrix is the world matrix of the particle system
  52788. * @param directionToUpdate is the direction vector to update with the result
  52789. * @param particle is the particle we are computed the direction for
  52790. */
  52791. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52792. if (this.angle === 0) {
  52793. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52794. }
  52795. else {
  52796. // measure the direction Vector from the emitter to the particle.
  52797. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52798. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52799. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52800. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52801. direction.x += randX;
  52802. direction.y += randY;
  52803. direction.z += randZ;
  52804. direction.normalize();
  52805. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52806. }
  52807. };
  52808. /**
  52809. * Called by the particle System when the position is computed for the created particle.
  52810. * @param worldMatrix is the world matrix of the particle system
  52811. * @param positionToUpdate is the position vector to update with the result
  52812. * @param particle is the particle we are computed the position for
  52813. */
  52814. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52815. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52816. var h = BABYLON.Scalar.RandomRange(0, 1);
  52817. // Better distribution in a cone at normal angles.
  52818. h = 1 - h * h;
  52819. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52820. radius = radius * h;
  52821. var randX = radius * Math.sin(s);
  52822. var randZ = radius * Math.cos(s);
  52823. var randY = h * this._height;
  52824. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52825. };
  52826. /**
  52827. * Clones the current emitter and returns a copy of it
  52828. * @returns the new emitter
  52829. */
  52830. ConeParticleEmitter.prototype.clone = function () {
  52831. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52832. BABYLON.Tools.DeepCopy(this, newOne);
  52833. return newOne;
  52834. };
  52835. /**
  52836. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52837. * @param effect defines the update shader
  52838. */
  52839. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52840. effect.setFloat("radius", this.radius);
  52841. effect.setFloat("angle", this.angle);
  52842. effect.setFloat("height", this._height);
  52843. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52844. };
  52845. /**
  52846. * Returns a string to use to update the GPU particles update shader
  52847. * @returns a string containng the defines string
  52848. */
  52849. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52850. return "#define CONEEMITTER";
  52851. };
  52852. /**
  52853. * Returns the string "BoxEmitter"
  52854. * @returns a string containing the class name
  52855. */
  52856. ConeParticleEmitter.prototype.getClassName = function () {
  52857. return "ConeEmitter";
  52858. };
  52859. /**
  52860. * Serializes the particle system to a JSON object.
  52861. * @returns the JSON object
  52862. */
  52863. ConeParticleEmitter.prototype.serialize = function () {
  52864. var serializationObject = {};
  52865. serializationObject.type = this.getClassName();
  52866. serializationObject.radius = this.radius;
  52867. serializationObject.angle = this.angle;
  52868. serializationObject.directionRandomizer = this.directionRandomizer;
  52869. return serializationObject;
  52870. };
  52871. /**
  52872. * Parse properties from a JSON object
  52873. * @param serializationObject defines the JSON object
  52874. */
  52875. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52876. this.radius = serializationObject.radius;
  52877. this.angle = serializationObject.angle;
  52878. this.directionRandomizer = serializationObject.directionRandomizer;
  52879. };
  52880. return ConeParticleEmitter;
  52881. }());
  52882. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52883. })(BABYLON || (BABYLON = {}));
  52884. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52885. "use strict";
  52886. var BABYLON;
  52887. (function (BABYLON) {
  52888. /**
  52889. * Particle emitter emitting particles from the inside of a sphere.
  52890. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52891. */
  52892. var SphereParticleEmitter = /** @class */ (function () {
  52893. /**
  52894. * Creates a new instance SphereParticleEmitter
  52895. * @param radius the radius of the emission sphere (1 by default)
  52896. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52897. */
  52898. function SphereParticleEmitter(
  52899. /**
  52900. * The radius of the emission sphere.
  52901. */
  52902. radius,
  52903. /**
  52904. * How much to randomize the particle direction [0-1].
  52905. */
  52906. directionRandomizer) {
  52907. if (radius === void 0) { radius = 1; }
  52908. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52909. this.radius = radius;
  52910. this.directionRandomizer = directionRandomizer;
  52911. }
  52912. /**
  52913. * Called by the particle System when the direction is computed for the created particle.
  52914. * @param emitPower is the power of the particle (speed)
  52915. * @param worldMatrix is the world matrix of the particle system
  52916. * @param directionToUpdate is the direction vector to update with the result
  52917. * @param particle is the particle we are computed the direction for
  52918. */
  52919. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52920. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52921. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52922. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52923. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52924. direction.x += randX;
  52925. direction.y += randY;
  52926. direction.z += randZ;
  52927. direction.normalize();
  52928. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52929. };
  52930. /**
  52931. * Called by the particle System when the position is computed for the created particle.
  52932. * @param worldMatrix is the world matrix of the particle system
  52933. * @param positionToUpdate is the position vector to update with the result
  52934. * @param particle is the particle we are computed the position for
  52935. */
  52936. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52937. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52938. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52939. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52940. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52941. var randY = randRadius * Math.cos(theta);
  52942. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52943. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52944. };
  52945. /**
  52946. * Clones the current emitter and returns a copy of it
  52947. * @returns the new emitter
  52948. */
  52949. SphereParticleEmitter.prototype.clone = function () {
  52950. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52951. BABYLON.Tools.DeepCopy(this, newOne);
  52952. return newOne;
  52953. };
  52954. /**
  52955. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52956. * @param effect defines the update shader
  52957. */
  52958. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52959. effect.setFloat("radius", this.radius);
  52960. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52961. };
  52962. /**
  52963. * Returns a string to use to update the GPU particles update shader
  52964. * @returns a string containng the defines string
  52965. */
  52966. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52967. return "#define SPHEREEMITTER";
  52968. };
  52969. /**
  52970. * Returns the string "SphereParticleEmitter"
  52971. * @returns a string containing the class name
  52972. */
  52973. SphereParticleEmitter.prototype.getClassName = function () {
  52974. return "SphereParticleEmitter";
  52975. };
  52976. /**
  52977. * Serializes the particle system to a JSON object.
  52978. * @returns the JSON object
  52979. */
  52980. SphereParticleEmitter.prototype.serialize = function () {
  52981. var serializationObject = {};
  52982. serializationObject.type = this.getClassName();
  52983. serializationObject.radius = this.radius;
  52984. serializationObject.directionRandomizer = this.directionRandomizer;
  52985. return serializationObject;
  52986. };
  52987. /**
  52988. * Parse properties from a JSON object
  52989. * @param serializationObject defines the JSON object
  52990. */
  52991. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52992. this.radius = serializationObject.radius;
  52993. this.directionRandomizer = serializationObject.directionRandomizer;
  52994. };
  52995. return SphereParticleEmitter;
  52996. }());
  52997. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52998. /**
  52999. * Particle emitter emitting particles from the inside of a sphere.
  53000. * It emits the particles randomly between two vectors.
  53001. */
  53002. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  53003. __extends(SphereDirectedParticleEmitter, _super);
  53004. /**
  53005. * Creates a new instance SphereDirectedParticleEmitter
  53006. * @param radius the radius of the emission sphere (1 by default)
  53007. * @param direction1 the min limit of the emission direction (up vector by default)
  53008. * @param direction2 the max limit of the emission direction (up vector by default)
  53009. */
  53010. function SphereDirectedParticleEmitter(radius,
  53011. /**
  53012. * The min limit of the emission direction.
  53013. */
  53014. direction1,
  53015. /**
  53016. * The max limit of the emission direction.
  53017. */
  53018. direction2) {
  53019. if (radius === void 0) { radius = 1; }
  53020. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  53021. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  53022. var _this = _super.call(this, radius) || this;
  53023. _this.direction1 = direction1;
  53024. _this.direction2 = direction2;
  53025. return _this;
  53026. }
  53027. /**
  53028. * Called by the particle System when the direction is computed for the created particle.
  53029. * @param emitPower is the power of the particle (speed)
  53030. * @param worldMatrix is the world matrix of the particle system
  53031. * @param directionToUpdate is the direction vector to update with the result
  53032. * @param particle is the particle we are computed the direction for
  53033. */
  53034. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  53035. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  53036. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  53037. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  53038. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  53039. };
  53040. /**
  53041. * Clones the current emitter and returns a copy of it
  53042. * @returns the new emitter
  53043. */
  53044. SphereDirectedParticleEmitter.prototype.clone = function () {
  53045. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  53046. BABYLON.Tools.DeepCopy(this, newOne);
  53047. return newOne;
  53048. };
  53049. /**
  53050. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  53051. * @param effect defines the update shader
  53052. */
  53053. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  53054. effect.setFloat("radius", this.radius);
  53055. effect.setVector3("direction1", this.direction1);
  53056. effect.setVector3("direction2", this.direction2);
  53057. };
  53058. /**
  53059. * Returns a string to use to update the GPU particles update shader
  53060. * @returns a string containng the defines string
  53061. */
  53062. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  53063. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  53064. };
  53065. /**
  53066. * Returns the string "SphereDirectedParticleEmitter"
  53067. * @returns a string containing the class name
  53068. */
  53069. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  53070. return "SphereDirectedParticleEmitter";
  53071. };
  53072. /**
  53073. * Serializes the particle system to a JSON object.
  53074. * @returns the JSON object
  53075. */
  53076. SphereDirectedParticleEmitter.prototype.serialize = function () {
  53077. var serializationObject = _super.prototype.serialize.call(this);
  53078. ;
  53079. serializationObject.direction1 = this.direction1.asArray();
  53080. ;
  53081. serializationObject.direction2 = this.direction2.asArray();
  53082. ;
  53083. return serializationObject;
  53084. };
  53085. /**
  53086. * Parse properties from a JSON object
  53087. * @param serializationObject defines the JSON object
  53088. */
  53089. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  53090. _super.prototype.parse.call(this, serializationObject);
  53091. this.direction1.copyFrom(serializationObject.direction1);
  53092. this.direction2.copyFrom(serializationObject.direction2);
  53093. };
  53094. return SphereDirectedParticleEmitter;
  53095. }(SphereParticleEmitter));
  53096. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  53097. })(BABYLON || (BABYLON = {}));
  53098. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  53099. "use strict";
  53100. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53101. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53102. s = arguments[i];
  53103. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53104. t[p] = s[p];
  53105. }
  53106. return t;
  53107. };
  53108. var BABYLON;
  53109. (function (BABYLON) {
  53110. /**
  53111. * This represents a GPU particle system in Babylon
  53112. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  53113. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  53114. */
  53115. var GPUParticleSystem = /** @class */ (function () {
  53116. /**
  53117. * Instantiates a GPU particle system.
  53118. * 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.
  53119. * @param name The name of the particle system
  53120. * @param capacity The max number of particles alive at the same time
  53121. * @param scene The scene the particle system belongs to
  53122. */
  53123. function GPUParticleSystem(name, options, scene) {
  53124. /**
  53125. * The emitter represents the Mesh or position we are attaching the particle system to.
  53126. */
  53127. this.emitter = null;
  53128. /**
  53129. * The rendering group used by the Particle system to chose when to render.
  53130. */
  53131. this.renderingGroupId = 0;
  53132. /**
  53133. * The layer mask we are rendering the particles through.
  53134. */
  53135. this.layerMask = 0x0FFFFFFF;
  53136. this._targetIndex = 0;
  53137. this._currentRenderId = -1;
  53138. this._started = false;
  53139. this._stopped = false;
  53140. this._timeDelta = 0;
  53141. this._attributesStrideSize = 14;
  53142. this._actualFrame = 0;
  53143. /**
  53144. * List of animations used by the particle system.
  53145. */
  53146. this.animations = [];
  53147. /**
  53148. * An event triggered when the system is disposed.
  53149. */
  53150. this.onDisposeObservable = new BABYLON.Observable();
  53151. /**
  53152. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  53153. */
  53154. this.updateSpeed = 0.01;
  53155. /**
  53156. * The amount of time the particle system is running (depends of the overall update speed).
  53157. */
  53158. this.targetStopDuration = 0;
  53159. /**
  53160. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  53161. */
  53162. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  53163. /**
  53164. * Minimum life time of emitting particles.
  53165. */
  53166. this.minLifeTime = 1;
  53167. /**
  53168. * Maximum life time of emitting particles.
  53169. */
  53170. this.maxLifeTime = 1;
  53171. /**
  53172. * Minimum Size of emitting particles.
  53173. */
  53174. this.minSize = 1;
  53175. /**
  53176. * Maximum Size of emitting particles.
  53177. */
  53178. this.maxSize = 1;
  53179. /**
  53180. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53181. */
  53182. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53183. /**
  53184. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  53185. */
  53186. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53187. /**
  53188. * Color the particle will have at the end of its lifetime.
  53189. */
  53190. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  53191. /**
  53192. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  53193. */
  53194. this.emitRate = 100;
  53195. /**
  53196. * You can use gravity if you want to give an orientation to your particles.
  53197. */
  53198. this.gravity = BABYLON.Vector3.Zero();
  53199. /**
  53200. * Minimum power of emitting particles.
  53201. */
  53202. this.minEmitPower = 1;
  53203. /**
  53204. * Maximum power of emitting particles.
  53205. */
  53206. this.maxEmitPower = 1;
  53207. /**
  53208. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  53209. * to override the particles.
  53210. */
  53211. this.forceDepthWrite = false;
  53212. this.id = name;
  53213. this.name = name;
  53214. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53215. this._engine = this._scene.getEngine();
  53216. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  53217. this._capacity = fullOptions.capacity;
  53218. this._activeCount = fullOptions.capacity;
  53219. this._currentActiveCount = 0;
  53220. this._scene.particleSystems.push(this);
  53221. this._updateEffectOptions = {
  53222. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53223. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53224. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53225. uniformBuffersNames: [],
  53226. samplers: ["randomSampler"],
  53227. defines: "",
  53228. fallbacks: null,
  53229. onCompiled: null,
  53230. onError: null,
  53231. indexParameters: null,
  53232. maxSimultaneousLights: 0,
  53233. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53234. };
  53235. // Random data
  53236. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53237. var d = [];
  53238. for (var i = 0; i < maxTextureSize; ++i) {
  53239. d.push(Math.random());
  53240. d.push(Math.random());
  53241. d.push(Math.random());
  53242. d.push(Math.random());
  53243. }
  53244. 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);
  53245. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53246. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53247. this._randomTextureSize = maxTextureSize;
  53248. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53249. }
  53250. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53251. /**
  53252. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53253. */
  53254. get: function () {
  53255. if (!BABYLON.Engine.LastCreatedEngine) {
  53256. return false;
  53257. }
  53258. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53259. },
  53260. enumerable: true,
  53261. configurable: true
  53262. });
  53263. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53264. /**
  53265. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53266. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53267. */
  53268. get: function () {
  53269. if (this.particleEmitterType.direction1) {
  53270. return this.particleEmitterType.direction1;
  53271. }
  53272. return BABYLON.Vector3.Zero();
  53273. },
  53274. set: function (value) {
  53275. if (this.particleEmitterType.direction1) {
  53276. this.particleEmitterType.direction1 = value;
  53277. }
  53278. },
  53279. enumerable: true,
  53280. configurable: true
  53281. });
  53282. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53283. /**
  53284. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53285. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53286. */
  53287. get: function () {
  53288. if (this.particleEmitterType.direction2) {
  53289. return this.particleEmitterType.direction2;
  53290. }
  53291. return BABYLON.Vector3.Zero();
  53292. },
  53293. set: function (value) {
  53294. if (this.particleEmitterType.direction2) {
  53295. this.particleEmitterType.direction2 = value;
  53296. }
  53297. },
  53298. enumerable: true,
  53299. configurable: true
  53300. });
  53301. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53302. /**
  53303. * 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.
  53304. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53305. */
  53306. get: function () {
  53307. if (this.particleEmitterType.minEmitBox) {
  53308. return this.particleEmitterType.minEmitBox;
  53309. }
  53310. return BABYLON.Vector3.Zero();
  53311. },
  53312. set: function (value) {
  53313. if (this.particleEmitterType.minEmitBox) {
  53314. this.particleEmitterType.minEmitBox = value;
  53315. }
  53316. },
  53317. enumerable: true,
  53318. configurable: true
  53319. });
  53320. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53321. /**
  53322. * 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.
  53323. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53324. */
  53325. get: function () {
  53326. if (this.particleEmitterType.maxEmitBox) {
  53327. return this.particleEmitterType.maxEmitBox;
  53328. }
  53329. return BABYLON.Vector3.Zero();
  53330. },
  53331. set: function (value) {
  53332. if (this.particleEmitterType.maxEmitBox) {
  53333. this.particleEmitterType.maxEmitBox = value;
  53334. }
  53335. },
  53336. enumerable: true,
  53337. configurable: true
  53338. });
  53339. /**
  53340. * Gets the maximum number of particles active at the same time.
  53341. * @returns The max number of active particles.
  53342. */
  53343. GPUParticleSystem.prototype.getCapacity = function () {
  53344. return this._capacity;
  53345. };
  53346. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53347. /**
  53348. * Gets or set the number of active particles
  53349. */
  53350. get: function () {
  53351. return this._activeCount;
  53352. },
  53353. set: function (value) {
  53354. this._activeCount = Math.min(value, this._capacity);
  53355. },
  53356. enumerable: true,
  53357. configurable: true
  53358. });
  53359. /**
  53360. * Is this system ready to be used/rendered
  53361. * @return true if the system is ready
  53362. */
  53363. GPUParticleSystem.prototype.isReady = function () {
  53364. if (!this._updateEffect) {
  53365. this._recreateUpdateEffect();
  53366. this._recreateRenderEffect();
  53367. return false;
  53368. }
  53369. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53370. return false;
  53371. }
  53372. return true;
  53373. };
  53374. /**
  53375. * Gets Wether the system has been started.
  53376. * @returns True if it has been started, otherwise false.
  53377. */
  53378. GPUParticleSystem.prototype.isStarted = function () {
  53379. return this._started;
  53380. };
  53381. /**
  53382. * Starts the particle system and begins to emit.
  53383. */
  53384. GPUParticleSystem.prototype.start = function () {
  53385. this._started = true;
  53386. this._stopped = false;
  53387. };
  53388. /**
  53389. * Stops the particle system.
  53390. */
  53391. GPUParticleSystem.prototype.stop = function () {
  53392. this._stopped = true;
  53393. };
  53394. /**
  53395. * Remove all active particles
  53396. */
  53397. GPUParticleSystem.prototype.reset = function () {
  53398. this._releaseBuffers();
  53399. this._releaseVAOs();
  53400. this._currentActiveCount = 0;
  53401. this._targetIndex = 0;
  53402. };
  53403. /**
  53404. * Returns the string "GPUParticleSystem"
  53405. * @returns a string containing the class name
  53406. */
  53407. GPUParticleSystem.prototype.getClassName = function () {
  53408. return "GPUParticleSystem";
  53409. };
  53410. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53411. var updateVertexBuffers = {};
  53412. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53413. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53414. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53415. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53416. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53417. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53418. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53419. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53420. this._engine.bindArrayBuffer(null);
  53421. return vao;
  53422. };
  53423. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53424. var renderVertexBuffers = {};
  53425. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53426. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53427. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53428. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53429. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53430. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53431. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53432. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53433. this._engine.bindArrayBuffer(null);
  53434. return vao;
  53435. };
  53436. GPUParticleSystem.prototype._initialize = function (force) {
  53437. if (force === void 0) { force = false; }
  53438. if (this._buffer0 && !force) {
  53439. return;
  53440. }
  53441. var engine = this._scene.getEngine();
  53442. var data = new Array();
  53443. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53444. // position
  53445. data.push(0.0);
  53446. data.push(0.0);
  53447. data.push(0.0);
  53448. // Age and life
  53449. data.push(0.0); // create the particle as a dead one to create a new one at start
  53450. data.push(0.0);
  53451. // Seed
  53452. data.push(Math.random());
  53453. // Size
  53454. data.push(0.0);
  53455. // color
  53456. data.push(0.0);
  53457. data.push(0.0);
  53458. data.push(0.0);
  53459. data.push(0.0);
  53460. // direction
  53461. data.push(0.0);
  53462. data.push(0.0);
  53463. data.push(0.0);
  53464. }
  53465. // Sprite data
  53466. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53467. -0.5, 0.5, 0, 1,
  53468. -0.5, -0.5, 0, 0,
  53469. 0.5, -0.5, 1, 0]);
  53470. // Buffers
  53471. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53472. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53473. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53474. // Update VAO
  53475. this._updateVAO = [];
  53476. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53477. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53478. // Render VAO
  53479. this._renderVAO = [];
  53480. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53481. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53482. // Links
  53483. this._sourceBuffer = this._buffer0;
  53484. this._targetBuffer = this._buffer1;
  53485. };
  53486. /** @ignore */
  53487. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53488. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53489. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53490. return;
  53491. }
  53492. this._updateEffectOptions.defines = defines;
  53493. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53494. };
  53495. /** @ignore */
  53496. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53497. var defines = "";
  53498. if (this._scene.clipPlane) {
  53499. defines = "\n#define CLIPPLANE";
  53500. }
  53501. if (this._renderEffect && this._renderEffect.defines === defines) {
  53502. return;
  53503. }
  53504. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53505. };
  53506. /**
  53507. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53508. */
  53509. GPUParticleSystem.prototype.animate = function () {
  53510. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53511. this._actualFrame += this._timeDelta;
  53512. if (!this._stopped) {
  53513. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53514. this.stop();
  53515. }
  53516. }
  53517. };
  53518. /**
  53519. * Renders the particle system in its current state.
  53520. * @returns the current number of particles
  53521. */
  53522. GPUParticleSystem.prototype.render = function () {
  53523. if (!this._started) {
  53524. return 0;
  53525. }
  53526. this._recreateUpdateEffect();
  53527. this._recreateRenderEffect();
  53528. if (!this.isReady()) {
  53529. return 0;
  53530. }
  53531. if (this._currentRenderId === this._scene.getRenderId()) {
  53532. return 0;
  53533. }
  53534. this._currentRenderId = this._scene.getRenderId();
  53535. // Get everything ready to render
  53536. this._initialize();
  53537. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53538. // Enable update effect
  53539. this._engine.enableEffect(this._updateEffect);
  53540. this._engine.setState(false);
  53541. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53542. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53543. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53544. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53545. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53546. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53547. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53548. this._updateEffect.setDirectColor4("color1", this.color1);
  53549. this._updateEffect.setDirectColor4("color2", this.color2);
  53550. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53551. this._updateEffect.setVector3("gravity", this.gravity);
  53552. if (this.particleEmitterType) {
  53553. this.particleEmitterType.applyToShader(this._updateEffect);
  53554. }
  53555. var emitterWM;
  53556. if (this.emitter.position) {
  53557. var emitterMesh = this.emitter;
  53558. emitterWM = emitterMesh.getWorldMatrix();
  53559. }
  53560. else {
  53561. var emitterPosition = this.emitter;
  53562. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53563. }
  53564. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53565. // Bind source VAO
  53566. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53567. // Update
  53568. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53569. this._engine.setRasterizerState(false);
  53570. this._engine.beginTransformFeedback();
  53571. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53572. this._engine.endTransformFeedback();
  53573. this._engine.setRasterizerState(true);
  53574. this._engine.bindTransformFeedbackBuffer(null);
  53575. // Enable render effect
  53576. this._engine.enableEffect(this._renderEffect);
  53577. var viewMatrix = this._scene.getViewMatrix();
  53578. this._renderEffect.setMatrix("view", viewMatrix);
  53579. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53580. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53581. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53582. if (this._scene.clipPlane) {
  53583. var clipPlane = this._scene.clipPlane;
  53584. var invView = viewMatrix.clone();
  53585. invView.invert();
  53586. this._renderEffect.setMatrix("invView", invView);
  53587. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53588. }
  53589. // Draw order
  53590. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53591. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53592. }
  53593. else {
  53594. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53595. }
  53596. if (this.forceDepthWrite) {
  53597. this._engine.setDepthWrite(true);
  53598. }
  53599. // Bind source VAO
  53600. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53601. // Render
  53602. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53603. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53604. // Switch VAOs
  53605. this._targetIndex++;
  53606. if (this._targetIndex === 2) {
  53607. this._targetIndex = 0;
  53608. }
  53609. // Switch buffers
  53610. var tmpBuffer = this._sourceBuffer;
  53611. this._sourceBuffer = this._targetBuffer;
  53612. this._targetBuffer = tmpBuffer;
  53613. return this._currentActiveCount;
  53614. };
  53615. /**
  53616. * Rebuilds the particle system
  53617. */
  53618. GPUParticleSystem.prototype.rebuild = function () {
  53619. this._initialize(true);
  53620. };
  53621. GPUParticleSystem.prototype._releaseBuffers = function () {
  53622. if (this._buffer0) {
  53623. this._buffer0.dispose();
  53624. this._buffer0 = null;
  53625. }
  53626. if (this._buffer1) {
  53627. this._buffer1.dispose();
  53628. this._buffer1 = null;
  53629. }
  53630. if (this._spriteBuffer) {
  53631. this._spriteBuffer.dispose();
  53632. this._spriteBuffer = null;
  53633. }
  53634. };
  53635. GPUParticleSystem.prototype._releaseVAOs = function () {
  53636. if (!this._updateVAO) {
  53637. return;
  53638. }
  53639. for (var index = 0; index < this._updateVAO.length; index++) {
  53640. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53641. }
  53642. this._updateVAO = [];
  53643. for (var index = 0; index < this._renderVAO.length; index++) {
  53644. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53645. }
  53646. this._renderVAO = [];
  53647. };
  53648. /**
  53649. * Disposes the particle system and free the associated resources
  53650. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53651. */
  53652. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53653. if (disposeTexture === void 0) { disposeTexture = true; }
  53654. var index = this._scene.particleSystems.indexOf(this);
  53655. if (index > -1) {
  53656. this._scene.particleSystems.splice(index, 1);
  53657. }
  53658. this._releaseBuffers();
  53659. this._releaseVAOs();
  53660. if (this._randomTexture) {
  53661. this._randomTexture.dispose();
  53662. this._randomTexture = null;
  53663. }
  53664. if (disposeTexture && this.particleTexture) {
  53665. this.particleTexture.dispose();
  53666. this.particleTexture = null;
  53667. }
  53668. // Callback
  53669. this.onDisposeObservable.notifyObservers(this);
  53670. this.onDisposeObservable.clear();
  53671. };
  53672. /**
  53673. * Clones the particle system.
  53674. * @param name The name of the cloned object
  53675. * @param newEmitter The new emitter to use
  53676. * @returns the cloned particle system
  53677. */
  53678. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53679. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53680. BABYLON.Tools.DeepCopy(this, result);
  53681. if (newEmitter === undefined) {
  53682. newEmitter = this.emitter;
  53683. }
  53684. result.emitter = newEmitter;
  53685. if (this.particleTexture) {
  53686. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53687. }
  53688. return result;
  53689. };
  53690. /**
  53691. * Serializes the particle system to a JSON object.
  53692. * @returns the JSON object
  53693. */
  53694. GPUParticleSystem.prototype.serialize = function () {
  53695. var serializationObject = {};
  53696. serializationObject.name = this.name;
  53697. serializationObject.id = this.id;
  53698. // Emitter
  53699. if (this.emitter.position) {
  53700. var emitterMesh = this.emitter;
  53701. serializationObject.emitterId = emitterMesh.id;
  53702. }
  53703. else {
  53704. var emitterPosition = this.emitter;
  53705. serializationObject.emitter = emitterPosition.asArray();
  53706. }
  53707. serializationObject.capacity = this.getCapacity();
  53708. if (this.particleTexture) {
  53709. serializationObject.textureName = this.particleTexture.name;
  53710. }
  53711. // Animations
  53712. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53713. // Particle system
  53714. serializationObject.activeParticleCount = this.activeParticleCount;
  53715. serializationObject.randomTextureSize = this._randomTextureSize;
  53716. serializationObject.minSize = this.minSize;
  53717. serializationObject.maxSize = this.maxSize;
  53718. serializationObject.minEmitPower = this.minEmitPower;
  53719. serializationObject.maxEmitPower = this.maxEmitPower;
  53720. serializationObject.minLifeTime = this.minLifeTime;
  53721. serializationObject.maxLifeTime = this.maxLifeTime;
  53722. serializationObject.emitRate = this.emitRate;
  53723. serializationObject.gravity = this.gravity.asArray();
  53724. serializationObject.color1 = this.color1.asArray();
  53725. serializationObject.color2 = this.color2.asArray();
  53726. serializationObject.colorDead = this.colorDead.asArray();
  53727. serializationObject.updateSpeed = this.updateSpeed;
  53728. serializationObject.targetStopDuration = this.targetStopDuration;
  53729. serializationObject.blendMode = this.blendMode;
  53730. // Emitter
  53731. if (this.particleEmitterType) {
  53732. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53733. }
  53734. return serializationObject;
  53735. };
  53736. /**
  53737. * Parses a JSON object to create a GPU particle system.
  53738. * @param parsedParticleSystem The JSON object to parse
  53739. * @param scene The scene to create the particle system in
  53740. * @param rootUrl The root url to use to load external dependencies like texture
  53741. * @returns the parsed GPU particle system
  53742. */
  53743. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53744. var name = parsedParticleSystem.name;
  53745. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53746. if (parsedParticleSystem.id) {
  53747. particleSystem.id = parsedParticleSystem.id;
  53748. }
  53749. // Texture
  53750. if (parsedParticleSystem.textureName) {
  53751. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53752. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53753. }
  53754. // Emitter
  53755. if (parsedParticleSystem.emitterId) {
  53756. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53757. }
  53758. else {
  53759. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53760. }
  53761. // Animations
  53762. if (parsedParticleSystem.animations) {
  53763. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53764. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53765. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53766. }
  53767. }
  53768. // Particle system
  53769. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53770. particleSystem.minSize = parsedParticleSystem.minSize;
  53771. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53772. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53773. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53774. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53775. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53776. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53777. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53778. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53779. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53780. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53781. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53782. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53783. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53784. // Emitter
  53785. if (parsedParticleSystem.particleEmitterType) {
  53786. var emitterType = void 0;
  53787. switch (parsedParticleSystem.particleEmitterType.type) {
  53788. case "SphereEmitter":
  53789. emitterType = new BABYLON.SphereParticleEmitter();
  53790. break;
  53791. case "SphereDirectedParticleEmitter":
  53792. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53793. break;
  53794. case "ConeEmitter":
  53795. emitterType = new BABYLON.ConeParticleEmitter();
  53796. break;
  53797. case "BoxEmitter":
  53798. default:
  53799. emitterType = new BABYLON.BoxParticleEmitter();
  53800. break;
  53801. }
  53802. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53803. particleSystem.particleEmitterType = emitterType;
  53804. }
  53805. return particleSystem;
  53806. };
  53807. return GPUParticleSystem;
  53808. }());
  53809. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53810. })(BABYLON || (BABYLON = {}));
  53811. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53812. "use strict";
  53813. var BABYLON;
  53814. (function (BABYLON) {
  53815. /**
  53816. * Represents one particle of a solid particle system.
  53817. */
  53818. var SolidParticle = /** @class */ (function () {
  53819. /**
  53820. * Creates a Solid Particle object.
  53821. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53822. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53823. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53824. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53825. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53826. * @param shapeId (integer) is the model shape identifier in the SPS.
  53827. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53828. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53829. */
  53830. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53831. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53832. /**
  53833. * particle global index
  53834. */
  53835. this.idx = 0;
  53836. /**
  53837. * The color of the particle
  53838. */
  53839. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53840. /**
  53841. * The world space position of the particle.
  53842. */
  53843. this.position = BABYLON.Vector3.Zero();
  53844. /**
  53845. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53846. */
  53847. this.rotation = BABYLON.Vector3.Zero();
  53848. /**
  53849. * The scaling of the particle.
  53850. */
  53851. this.scaling = BABYLON.Vector3.One();
  53852. /**
  53853. * The uvs of the particle.
  53854. */
  53855. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53856. /**
  53857. * The current speed of the particle.
  53858. */
  53859. this.velocity = BABYLON.Vector3.Zero();
  53860. /**
  53861. * The pivot point in the particle local space.
  53862. */
  53863. this.pivot = BABYLON.Vector3.Zero();
  53864. /**
  53865. * Must the particle be translated from its pivot point in its local space ?
  53866. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53867. * Default : false
  53868. */
  53869. this.translateFromPivot = false;
  53870. /**
  53871. * Is the particle active or not ?
  53872. */
  53873. this.alive = true;
  53874. /**
  53875. * Is the particle visible or not ?
  53876. */
  53877. this.isVisible = true;
  53878. /**
  53879. * Index of this particle in the global "positions" array (Internal use)
  53880. */
  53881. this._pos = 0;
  53882. /**
  53883. * Index of this particle in the global "indices" array (Internal use)
  53884. */
  53885. this._ind = 0;
  53886. /**
  53887. * ModelShape id of this particle
  53888. */
  53889. this.shapeId = 0;
  53890. /**
  53891. * Index of the particle in its shape id (Internal use)
  53892. */
  53893. this.idxInShape = 0;
  53894. /**
  53895. * Still set as invisible in order to skip useless computations (Internal use)
  53896. */
  53897. this._stillInvisible = false;
  53898. /**
  53899. * Last computed particle rotation matrix
  53900. */
  53901. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53902. /**
  53903. * Parent particle Id, if any.
  53904. * Default null.
  53905. */
  53906. this.parentId = null;
  53907. /**
  53908. * Internal global position in the SPS.
  53909. */
  53910. this._globalPosition = BABYLON.Vector3.Zero();
  53911. this.idx = particleIndex;
  53912. this._pos = positionIndex;
  53913. this._ind = indiceIndex;
  53914. this._model = model;
  53915. this.shapeId = shapeId;
  53916. this.idxInShape = idxInShape;
  53917. this._sps = sps;
  53918. if (modelBoundingInfo) {
  53919. this._modelBoundingInfo = modelBoundingInfo;
  53920. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53921. }
  53922. }
  53923. Object.defineProperty(SolidParticle.prototype, "scale", {
  53924. /**
  53925. * Legacy support, changed scale to scaling
  53926. */
  53927. get: function () {
  53928. return this.scaling;
  53929. },
  53930. /**
  53931. * Legacy support, changed scale to scaling
  53932. */
  53933. set: function (scale) {
  53934. this.scaling = scale;
  53935. },
  53936. enumerable: true,
  53937. configurable: true
  53938. });
  53939. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53940. /**
  53941. * Legacy support, changed quaternion to rotationQuaternion
  53942. */
  53943. get: function () {
  53944. return this.rotationQuaternion;
  53945. },
  53946. /**
  53947. * Legacy support, changed quaternion to rotationQuaternion
  53948. */
  53949. set: function (q) {
  53950. this.rotationQuaternion = q;
  53951. },
  53952. enumerable: true,
  53953. configurable: true
  53954. });
  53955. /**
  53956. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53957. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53958. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53959. * @returns true if it intersects
  53960. */
  53961. SolidParticle.prototype.intersectsMesh = function (target) {
  53962. if (!this._boundingInfo || !target._boundingInfo) {
  53963. return false;
  53964. }
  53965. if (this._sps._bSphereOnly) {
  53966. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53967. }
  53968. return this._boundingInfo.intersects(target._boundingInfo, false);
  53969. };
  53970. return SolidParticle;
  53971. }());
  53972. BABYLON.SolidParticle = SolidParticle;
  53973. /**
  53974. * Represents the shape of the model used by one particle of a solid particle system.
  53975. * SPS internal tool, don't use it manually.
  53976. */
  53977. var ModelShape = /** @class */ (function () {
  53978. /**
  53979. * 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.
  53980. * SPS internal tool, don't use it manually.
  53981. * @ignore
  53982. */
  53983. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53984. /**
  53985. * length of the shape in the model indices array (internal use)
  53986. */
  53987. this._indicesLength = 0;
  53988. this.shapeID = id;
  53989. this._shape = shape;
  53990. this._indicesLength = indicesLength;
  53991. this._shapeUV = shapeUV;
  53992. this._positionFunction = posFunction;
  53993. this._vertexFunction = vtxFunction;
  53994. }
  53995. return ModelShape;
  53996. }());
  53997. BABYLON.ModelShape = ModelShape;
  53998. /**
  53999. * Represents a Depth Sorted Particle in the solid particle system.
  54000. */
  54001. var DepthSortedParticle = /** @class */ (function () {
  54002. function DepthSortedParticle() {
  54003. /**
  54004. * Index of the particle in the "indices" array
  54005. */
  54006. this.ind = 0;
  54007. /**
  54008. * Length of the particle shape in the "indices" array
  54009. */
  54010. this.indicesLength = 0;
  54011. /**
  54012. * Squared distance from the particle to the camera
  54013. */
  54014. this.sqDistance = 0.0;
  54015. }
  54016. return DepthSortedParticle;
  54017. }());
  54018. BABYLON.DepthSortedParticle = DepthSortedParticle;
  54019. })(BABYLON || (BABYLON = {}));
  54020. //# sourceMappingURL=babylon.solidParticle.js.map
  54021. "use strict";
  54022. var BABYLON;
  54023. (function (BABYLON) {
  54024. /**
  54025. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  54026. *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.
  54027. * The SPS is also a particle system. It provides some methods to manage the particles.
  54028. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  54029. *
  54030. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  54031. */
  54032. var SolidParticleSystem = /** @class */ (function () {
  54033. /**
  54034. * Creates a SPS (Solid Particle System) object.
  54035. * @param name (String) is the SPS name, this will be the underlying mesh name.
  54036. * @param scene (Scene) is the scene in which the SPS is added.
  54037. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  54038. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  54039. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  54040. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  54041. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  54042. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  54043. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  54044. */
  54045. function SolidParticleSystem(name, scene, options) {
  54046. /**
  54047. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  54048. * Example : var p = SPS.particles[i];
  54049. */
  54050. this.particles = new Array();
  54051. /**
  54052. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  54053. */
  54054. this.nbParticles = 0;
  54055. /**
  54056. * If the particles must ever face the camera (default false). Useful for planar particles.
  54057. */
  54058. this.billboard = false;
  54059. /**
  54060. * Recompute normals when adding a shape
  54061. */
  54062. this.recomputeNormals = true;
  54063. /**
  54064. * This a counter ofr your own usage. It's not set by any SPS functions.
  54065. */
  54066. this.counter = 0;
  54067. /**
  54068. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  54069. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  54070. */
  54071. this.vars = {};
  54072. /**
  54073. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  54074. */
  54075. this._bSphereOnly = false;
  54076. /**
  54077. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  54078. */
  54079. this._bSphereRadiusFactor = 1.0;
  54080. this._positions = new Array();
  54081. this._indices = new Array();
  54082. this._normals = new Array();
  54083. this._colors = new Array();
  54084. this._uvs = new Array();
  54085. this._index = 0; // indices index
  54086. this._updatable = true;
  54087. this._pickable = false;
  54088. this._isVisibilityBoxLocked = false;
  54089. this._alwaysVisible = false;
  54090. this._depthSort = false;
  54091. this._shapeCounter = 0;
  54092. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  54093. this._color = new BABYLON.Color4(0, 0, 0, 0);
  54094. this._computeParticleColor = true;
  54095. this._computeParticleTexture = true;
  54096. this._computeParticleRotation = true;
  54097. this._computeParticleVertex = false;
  54098. this._computeBoundingBox = false;
  54099. this._depthSortParticles = true;
  54100. this._cam_axisZ = BABYLON.Vector3.Zero();
  54101. this._cam_axisY = BABYLON.Vector3.Zero();
  54102. this._cam_axisX = BABYLON.Vector3.Zero();
  54103. this._axisZ = BABYLON.Axis.Z;
  54104. this._camDir = BABYLON.Vector3.Zero();
  54105. this._camInvertedPosition = BABYLON.Vector3.Zero();
  54106. this._rotMatrix = new BABYLON.Matrix();
  54107. this._invertMatrix = new BABYLON.Matrix();
  54108. this._rotated = BABYLON.Vector3.Zero();
  54109. this._quaternion = new BABYLON.Quaternion();
  54110. this._vertex = BABYLON.Vector3.Zero();
  54111. this._normal = BABYLON.Vector3.Zero();
  54112. this._yaw = 0.0;
  54113. this._pitch = 0.0;
  54114. this._roll = 0.0;
  54115. this._halfroll = 0.0;
  54116. this._halfpitch = 0.0;
  54117. this._halfyaw = 0.0;
  54118. this._sinRoll = 0.0;
  54119. this._cosRoll = 0.0;
  54120. this._sinPitch = 0.0;
  54121. this._cosPitch = 0.0;
  54122. this._sinYaw = 0.0;
  54123. this._cosYaw = 0.0;
  54124. this._mustUnrotateFixedNormals = false;
  54125. this._minimum = BABYLON.Vector3.Zero();
  54126. this._maximum = BABYLON.Vector3.Zero();
  54127. this._minBbox = BABYLON.Vector3.Zero();
  54128. this._maxBbox = BABYLON.Vector3.Zero();
  54129. this._particlesIntersect = false;
  54130. this._depthSortFunction = function (p1, p2) {
  54131. return (p2.sqDistance - p1.sqDistance);
  54132. };
  54133. this._needs32Bits = false;
  54134. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  54135. this._scaledPivot = BABYLON.Vector3.Zero();
  54136. this._particleHasParent = false;
  54137. this.name = name;
  54138. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54139. this._camera = scene.activeCamera;
  54140. this._pickable = options ? options.isPickable : false;
  54141. this._depthSort = options ? options.enableDepthSort : false;
  54142. this._particlesIntersect = options ? options.particleIntersection : false;
  54143. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  54144. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  54145. if (options && options.updatable) {
  54146. this._updatable = options.updatable;
  54147. }
  54148. else {
  54149. this._updatable = true;
  54150. }
  54151. if (this._pickable) {
  54152. this.pickedParticles = [];
  54153. }
  54154. if (this._depthSort) {
  54155. this.depthSortedParticles = [];
  54156. }
  54157. }
  54158. /**
  54159. * Builds the SPS underlying mesh. Returns a standard Mesh.
  54160. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  54161. * @returns the created mesh
  54162. */
  54163. SolidParticleSystem.prototype.buildMesh = function () {
  54164. if (this.nbParticles === 0) {
  54165. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  54166. this.addShape(triangle, 1);
  54167. triangle.dispose();
  54168. }
  54169. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  54170. this._positions32 = new Float32Array(this._positions);
  54171. this._uvs32 = new Float32Array(this._uvs);
  54172. this._colors32 = new Float32Array(this._colors);
  54173. if (this.recomputeNormals) {
  54174. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  54175. }
  54176. this._normals32 = new Float32Array(this._normals);
  54177. this._fixedNormal32 = new Float32Array(this._normals);
  54178. if (this._mustUnrotateFixedNormals) {
  54179. this._unrotateFixedNormals();
  54180. }
  54181. var vertexData = new BABYLON.VertexData();
  54182. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  54183. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  54184. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  54185. if (this._uvs32) {
  54186. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  54187. ;
  54188. }
  54189. if (this._colors32) {
  54190. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  54191. }
  54192. var mesh = new BABYLON.Mesh(this.name, this._scene);
  54193. vertexData.applyToMesh(mesh, this._updatable);
  54194. this.mesh = mesh;
  54195. this.mesh.isPickable = this._pickable;
  54196. // free memory
  54197. if (!this._depthSort) {
  54198. this._indices = null;
  54199. }
  54200. this._positions = null;
  54201. this._normals = null;
  54202. this._uvs = null;
  54203. this._colors = null;
  54204. if (!this._updatable) {
  54205. this.particles.length = 0;
  54206. }
  54207. return mesh;
  54208. };
  54209. /**
  54210. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  54211. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  54212. * Thus the particles generated from `digest()` have their property `position` set yet.
  54213. * @param mesh ( Mesh ) is the mesh to be digested
  54214. * @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
  54215. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  54216. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  54217. * @returns the current SPS
  54218. */
  54219. SolidParticleSystem.prototype.digest = function (mesh, options) {
  54220. var size = (options && options.facetNb) || 1;
  54221. var number = (options && options.number) || 0;
  54222. var delta = (options && options.delta) || 0;
  54223. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54224. var meshInd = mesh.getIndices();
  54225. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54226. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54227. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54228. var f = 0; // facet counter
  54229. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54230. // compute size from number
  54231. if (number) {
  54232. number = (number > totalFacets) ? totalFacets : number;
  54233. size = Math.round(totalFacets / number);
  54234. delta = 0;
  54235. }
  54236. else {
  54237. size = (size > totalFacets) ? totalFacets : size;
  54238. }
  54239. var facetPos = []; // submesh positions
  54240. var facetInd = []; // submesh indices
  54241. var facetUV = []; // submesh UV
  54242. var facetCol = []; // submesh colors
  54243. var barycenter = BABYLON.Vector3.Zero();
  54244. var sizeO = size;
  54245. while (f < totalFacets) {
  54246. size = sizeO + Math.floor((1 + delta) * Math.random());
  54247. if (f > totalFacets - size) {
  54248. size = totalFacets - f;
  54249. }
  54250. // reset temp arrays
  54251. facetPos.length = 0;
  54252. facetInd.length = 0;
  54253. facetUV.length = 0;
  54254. facetCol.length = 0;
  54255. // iterate over "size" facets
  54256. var fi = 0;
  54257. for (var j = f * 3; j < (f + size) * 3; j++) {
  54258. facetInd.push(fi);
  54259. var i = meshInd[j];
  54260. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54261. if (meshUV) {
  54262. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54263. }
  54264. if (meshCol) {
  54265. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54266. }
  54267. fi++;
  54268. }
  54269. // create a model shape for each single particle
  54270. var idx = this.nbParticles;
  54271. var shape = this._posToShape(facetPos);
  54272. var shapeUV = this._uvsToShapeUV(facetUV);
  54273. // compute the barycenter of the shape
  54274. var v;
  54275. for (v = 0; v < shape.length; v++) {
  54276. barycenter.addInPlace(shape[v]);
  54277. }
  54278. barycenter.scaleInPlace(1 / shape.length);
  54279. // shift the shape from its barycenter to the origin
  54280. for (v = 0; v < shape.length; v++) {
  54281. shape[v].subtractInPlace(barycenter);
  54282. }
  54283. var bInfo;
  54284. if (this._particlesIntersect) {
  54285. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54286. }
  54287. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54288. // add the particle in the SPS
  54289. var currentPos = this._positions.length;
  54290. var currentInd = this._indices.length;
  54291. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54292. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54293. // initialize the particle position
  54294. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54295. this._index += shape.length;
  54296. idx++;
  54297. this.nbParticles++;
  54298. this._shapeCounter++;
  54299. f += size;
  54300. }
  54301. return this;
  54302. };
  54303. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54304. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54305. var index = 0;
  54306. var idx = 0;
  54307. for (var p = 0; p < this.particles.length; p++) {
  54308. this._particle = this.particles[p];
  54309. this._shape = this._particle._model._shape;
  54310. if (this._particle.rotationQuaternion) {
  54311. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54312. }
  54313. else {
  54314. this._yaw = this._particle.rotation.y;
  54315. this._pitch = this._particle.rotation.x;
  54316. this._roll = this._particle.rotation.z;
  54317. this._quaternionRotationYPR();
  54318. }
  54319. this._quaternionToRotationMatrix();
  54320. this._rotMatrix.invertToRef(this._invertMatrix);
  54321. for (var pt = 0; pt < this._shape.length; pt++) {
  54322. idx = index + pt * 3;
  54323. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54324. this._fixedNormal32[idx] = this._normal.x;
  54325. this._fixedNormal32[idx + 1] = this._normal.y;
  54326. this._fixedNormal32[idx + 2] = this._normal.z;
  54327. }
  54328. index = idx + 3;
  54329. }
  54330. };
  54331. //reset copy
  54332. SolidParticleSystem.prototype._resetCopy = function () {
  54333. this._copy.position.x = 0;
  54334. this._copy.position.y = 0;
  54335. this._copy.position.z = 0;
  54336. this._copy.rotation.x = 0;
  54337. this._copy.rotation.y = 0;
  54338. this._copy.rotation.z = 0;
  54339. this._copy.rotationQuaternion = null;
  54340. this._copy.scaling.x = 1.0;
  54341. this._copy.scaling.y = 1.0;
  54342. this._copy.scaling.z = 1.0;
  54343. this._copy.uvs.x = 0;
  54344. this._copy.uvs.y = 0;
  54345. this._copy.uvs.z = 1.0;
  54346. this._copy.uvs.w = 1.0;
  54347. this._copy.color = null;
  54348. this._copy.translateFromPivot = false;
  54349. };
  54350. // _meshBuilder : inserts the shape model in the global SPS mesh
  54351. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54352. var i;
  54353. var u = 0;
  54354. var c = 0;
  54355. var n = 0;
  54356. this._resetCopy();
  54357. if (options && options.positionFunction) {
  54358. options.positionFunction(this._copy, idx, idxInShape);
  54359. this._mustUnrotateFixedNormals = true;
  54360. }
  54361. if (this._copy.rotationQuaternion) {
  54362. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54363. }
  54364. else {
  54365. this._yaw = this._copy.rotation.y;
  54366. this._pitch = this._copy.rotation.x;
  54367. this._roll = this._copy.rotation.z;
  54368. this._quaternionRotationYPR();
  54369. }
  54370. this._quaternionToRotationMatrix();
  54371. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54372. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54373. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54374. if (this._copy.translateFromPivot) {
  54375. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54376. }
  54377. else {
  54378. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54379. }
  54380. for (i = 0; i < shape.length; i++) {
  54381. this._vertex.x = shape[i].x;
  54382. this._vertex.y = shape[i].y;
  54383. this._vertex.z = shape[i].z;
  54384. if (options && options.vertexFunction) {
  54385. options.vertexFunction(this._copy, this._vertex, i);
  54386. }
  54387. this._vertex.x *= this._copy.scaling.x;
  54388. this._vertex.y *= this._copy.scaling.y;
  54389. this._vertex.z *= this._copy.scaling.z;
  54390. this._vertex.x -= this._scaledPivot.x;
  54391. this._vertex.y -= this._scaledPivot.y;
  54392. this._vertex.z -= this._scaledPivot.z;
  54393. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54394. this._rotated.addInPlace(this._pivotBackTranslation);
  54395. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54396. if (meshUV) {
  54397. 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);
  54398. u += 2;
  54399. }
  54400. if (this._copy.color) {
  54401. this._color = this._copy.color;
  54402. }
  54403. else if (meshCol && meshCol[c] !== undefined) {
  54404. this._color.r = meshCol[c];
  54405. this._color.g = meshCol[c + 1];
  54406. this._color.b = meshCol[c + 2];
  54407. this._color.a = meshCol[c + 3];
  54408. }
  54409. else {
  54410. this._color.r = 1.0;
  54411. this._color.g = 1.0;
  54412. this._color.b = 1.0;
  54413. this._color.a = 1.0;
  54414. }
  54415. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54416. c += 4;
  54417. if (!this.recomputeNormals && meshNor) {
  54418. this._normal.x = meshNor[n];
  54419. this._normal.y = meshNor[n + 1];
  54420. this._normal.z = meshNor[n + 2];
  54421. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54422. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54423. n += 3;
  54424. }
  54425. }
  54426. for (i = 0; i < meshInd.length; i++) {
  54427. var current_ind = p + meshInd[i];
  54428. indices.push(current_ind);
  54429. if (current_ind > 65535) {
  54430. this._needs32Bits = true;
  54431. }
  54432. }
  54433. if (this._pickable) {
  54434. var nbfaces = meshInd.length / 3;
  54435. for (i = 0; i < nbfaces; i++) {
  54436. this.pickedParticles.push({ idx: idx, faceId: i });
  54437. }
  54438. }
  54439. if (this._depthSort) {
  54440. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54441. }
  54442. return this._copy;
  54443. };
  54444. // returns a shape array from positions array
  54445. SolidParticleSystem.prototype._posToShape = function (positions) {
  54446. var shape = [];
  54447. for (var i = 0; i < positions.length; i += 3) {
  54448. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54449. }
  54450. return shape;
  54451. };
  54452. // returns a shapeUV array from a Vector4 uvs
  54453. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54454. var shapeUV = [];
  54455. if (uvs) {
  54456. for (var i = 0; i < uvs.length; i++)
  54457. shapeUV.push(uvs[i]);
  54458. }
  54459. return shapeUV;
  54460. };
  54461. // adds a new particle object in the particles array
  54462. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54463. if (bInfo === void 0) { bInfo = null; }
  54464. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54465. this.particles.push(sp);
  54466. return sp;
  54467. };
  54468. /**
  54469. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54470. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54471. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54472. * @param nb (positive integer) the number of particles to be created from this model
  54473. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54474. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54475. * @returns the number of shapes in the system
  54476. */
  54477. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54478. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54479. var meshInd = mesh.getIndices();
  54480. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54481. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54482. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54483. var bbInfo;
  54484. if (this._particlesIntersect) {
  54485. bbInfo = mesh.getBoundingInfo();
  54486. }
  54487. var shape = this._posToShape(meshPos);
  54488. var shapeUV = this._uvsToShapeUV(meshUV);
  54489. var posfunc = options ? options.positionFunction : null;
  54490. var vtxfunc = options ? options.vertexFunction : null;
  54491. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54492. // particles
  54493. var sp;
  54494. var currentCopy;
  54495. var idx = this.nbParticles;
  54496. for (var i = 0; i < nb; i++) {
  54497. var currentPos = this._positions.length;
  54498. var currentInd = this._indices.length;
  54499. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54500. if (this._updatable) {
  54501. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54502. sp.position.copyFrom(currentCopy.position);
  54503. sp.rotation.copyFrom(currentCopy.rotation);
  54504. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54505. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54506. }
  54507. if (currentCopy.color && sp.color) {
  54508. sp.color.copyFrom(currentCopy.color);
  54509. }
  54510. sp.scaling.copyFrom(currentCopy.scaling);
  54511. sp.uvs.copyFrom(currentCopy.uvs);
  54512. }
  54513. this._index += shape.length;
  54514. idx++;
  54515. }
  54516. this.nbParticles += nb;
  54517. this._shapeCounter++;
  54518. return this._shapeCounter - 1;
  54519. };
  54520. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54521. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54522. this._resetCopy();
  54523. if (particle._model._positionFunction) {
  54524. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54525. }
  54526. if (this._copy.rotationQuaternion) {
  54527. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54528. }
  54529. else {
  54530. this._yaw = this._copy.rotation.y;
  54531. this._pitch = this._copy.rotation.x;
  54532. this._roll = this._copy.rotation.z;
  54533. this._quaternionRotationYPR();
  54534. }
  54535. this._quaternionToRotationMatrix();
  54536. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54537. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54538. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54539. if (this._copy.translateFromPivot) {
  54540. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54541. }
  54542. else {
  54543. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54544. }
  54545. this._shape = particle._model._shape;
  54546. for (var pt = 0; pt < this._shape.length; pt++) {
  54547. this._vertex.x = this._shape[pt].x;
  54548. this._vertex.y = this._shape[pt].y;
  54549. this._vertex.z = this._shape[pt].z;
  54550. if (particle._model._vertexFunction) {
  54551. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54552. }
  54553. this._vertex.x *= this._copy.scaling.x;
  54554. this._vertex.y *= this._copy.scaling.y;
  54555. this._vertex.z *= this._copy.scaling.z;
  54556. this._vertex.x -= this._scaledPivot.x;
  54557. this._vertex.y -= this._scaledPivot.y;
  54558. this._vertex.z -= this._scaledPivot.z;
  54559. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54560. this._rotated.addInPlace(this._pivotBackTranslation);
  54561. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54562. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54563. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54564. }
  54565. particle.position.x = 0.0;
  54566. particle.position.y = 0.0;
  54567. particle.position.z = 0.0;
  54568. particle.rotation.x = 0.0;
  54569. particle.rotation.y = 0.0;
  54570. particle.rotation.z = 0.0;
  54571. particle.rotationQuaternion = null;
  54572. particle.scaling.x = 1.0;
  54573. particle.scaling.y = 1.0;
  54574. particle.scaling.z = 1.0;
  54575. particle.uvs.x = 0.0;
  54576. particle.uvs.y = 0.0;
  54577. particle.uvs.z = 1.0;
  54578. particle.uvs.w = 1.0;
  54579. particle.pivot.x = 0.0;
  54580. particle.pivot.y = 0.0;
  54581. particle.pivot.z = 0.0;
  54582. particle.translateFromPivot = false;
  54583. particle.parentId = null;
  54584. };
  54585. /**
  54586. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54587. * @returns the SPS.
  54588. */
  54589. SolidParticleSystem.prototype.rebuildMesh = function () {
  54590. for (var p = 0; p < this.particles.length; p++) {
  54591. this._rebuildParticle(this.particles[p]);
  54592. }
  54593. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54594. return this;
  54595. };
  54596. /**
  54597. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54598. * This method calls `updateParticle()` for each particle of the SPS.
  54599. * For an animated SPS, it is usually called within the render loop.
  54600. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54601. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54602. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54603. * @returns the SPS.
  54604. */
  54605. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54606. if (start === void 0) { start = 0; }
  54607. if (end === void 0) { end = this.nbParticles - 1; }
  54608. if (update === void 0) { update = true; }
  54609. if (!this._updatable) {
  54610. return this;
  54611. }
  54612. // custom beforeUpdate
  54613. this.beforeUpdateParticles(start, end, update);
  54614. this._cam_axisX.x = 1.0;
  54615. this._cam_axisX.y = 0.0;
  54616. this._cam_axisX.z = 0.0;
  54617. this._cam_axisY.x = 0.0;
  54618. this._cam_axisY.y = 1.0;
  54619. this._cam_axisY.z = 0.0;
  54620. this._cam_axisZ.x = 0.0;
  54621. this._cam_axisZ.y = 0.0;
  54622. this._cam_axisZ.z = 1.0;
  54623. // cases when the World Matrix is to be computed first
  54624. if (this.billboard || this._depthSort) {
  54625. this.mesh.computeWorldMatrix(true);
  54626. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54627. }
  54628. // if the particles will always face the camera
  54629. if (this.billboard) {
  54630. // compute the camera position and un-rotate it by the current mesh rotation
  54631. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54632. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54633. this._cam_axisZ.normalize();
  54634. // same for camera up vector extracted from the cam view matrix
  54635. var view = this._camera.getViewMatrix(true);
  54636. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54637. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54638. this._cam_axisY.normalize();
  54639. this._cam_axisX.normalize();
  54640. }
  54641. // if depthSort, compute the camera global position in the mesh local system
  54642. if (this._depthSort) {
  54643. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54644. }
  54645. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54646. var idx = 0; // current position index in the global array positions32
  54647. var index = 0; // position start index in the global array positions32 of the current particle
  54648. var colidx = 0; // current color index in the global array colors32
  54649. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54650. var uvidx = 0; // current uv index in the global array uvs32
  54651. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54652. var pt = 0; // current index in the particle model shape
  54653. if (this.mesh.isFacetDataEnabled) {
  54654. this._computeBoundingBox = true;
  54655. }
  54656. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54657. if (this._computeBoundingBox) {
  54658. if (start == 0 && end == this.nbParticles - 1) {
  54659. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54660. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54661. }
  54662. else {
  54663. if (this.mesh._boundingInfo) {
  54664. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54665. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54666. }
  54667. }
  54668. }
  54669. // particle loop
  54670. index = this.particles[start]._pos;
  54671. var vpos = (index / 3) | 0;
  54672. colorIndex = vpos * 4;
  54673. uvIndex = vpos * 2;
  54674. for (var p = start; p <= end; p++) {
  54675. this._particle = this.particles[p];
  54676. this._shape = this._particle._model._shape;
  54677. this._shapeUV = this._particle._model._shapeUV;
  54678. // call to custom user function to update the particle properties
  54679. this.updateParticle(this._particle);
  54680. // camera-particle distance for depth sorting
  54681. if (this._depthSort && this._depthSortParticles) {
  54682. var dsp = this.depthSortedParticles[p];
  54683. dsp.ind = this._particle._ind;
  54684. dsp.indicesLength = this._particle._model._indicesLength;
  54685. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54686. }
  54687. // skip the computations for inactive or already invisible particles
  54688. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54689. // increment indexes for the next particle
  54690. pt = this._shape.length;
  54691. index += pt * 3;
  54692. colorIndex += pt * 4;
  54693. uvIndex += pt * 2;
  54694. continue;
  54695. }
  54696. if (this._particle.isVisible) {
  54697. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54698. this._particleHasParent = (this._particle.parentId !== null);
  54699. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54700. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54701. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54702. // particle rotation matrix
  54703. if (this.billboard) {
  54704. this._particle.rotation.x = 0.0;
  54705. this._particle.rotation.y = 0.0;
  54706. }
  54707. if (this._computeParticleRotation || this.billboard) {
  54708. if (this._particle.rotationQuaternion) {
  54709. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54710. }
  54711. else {
  54712. this._yaw = this._particle.rotation.y;
  54713. this._pitch = this._particle.rotation.x;
  54714. this._roll = this._particle.rotation.z;
  54715. this._quaternionRotationYPR();
  54716. }
  54717. this._quaternionToRotationMatrix();
  54718. }
  54719. if (this._particleHasParent) {
  54720. this._parent = this.particles[this._particle.parentId];
  54721. 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];
  54722. 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];
  54723. 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];
  54724. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54725. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54726. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54727. if (this._computeParticleRotation || this.billboard) {
  54728. 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];
  54729. 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];
  54730. 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];
  54731. 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];
  54732. 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];
  54733. 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];
  54734. 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];
  54735. 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];
  54736. 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];
  54737. }
  54738. }
  54739. else {
  54740. this._particle._globalPosition.x = this._particle.position.x;
  54741. this._particle._globalPosition.y = this._particle.position.y;
  54742. this._particle._globalPosition.z = this._particle.position.z;
  54743. if (this._computeParticleRotation || this.billboard) {
  54744. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54745. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54746. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54747. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54748. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54749. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54750. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54751. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54752. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54753. }
  54754. }
  54755. if (this._particle.translateFromPivot) {
  54756. this._pivotBackTranslation.x = 0.0;
  54757. this._pivotBackTranslation.y = 0.0;
  54758. this._pivotBackTranslation.z = 0.0;
  54759. }
  54760. else {
  54761. this._pivotBackTranslation.x = this._scaledPivot.x;
  54762. this._pivotBackTranslation.y = this._scaledPivot.y;
  54763. this._pivotBackTranslation.z = this._scaledPivot.z;
  54764. }
  54765. // particle vertex loop
  54766. for (pt = 0; pt < this._shape.length; pt++) {
  54767. idx = index + pt * 3;
  54768. colidx = colorIndex + pt * 4;
  54769. uvidx = uvIndex + pt * 2;
  54770. this._vertex.x = this._shape[pt].x;
  54771. this._vertex.y = this._shape[pt].y;
  54772. this._vertex.z = this._shape[pt].z;
  54773. if (this._computeParticleVertex) {
  54774. this.updateParticleVertex(this._particle, this._vertex, pt);
  54775. }
  54776. // positions
  54777. this._vertex.x *= this._particle.scaling.x;
  54778. this._vertex.y *= this._particle.scaling.y;
  54779. this._vertex.z *= this._particle.scaling.z;
  54780. this._vertex.x -= this._scaledPivot.x;
  54781. this._vertex.y -= this._scaledPivot.y;
  54782. this._vertex.z -= this._scaledPivot.z;
  54783. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54784. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54785. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54786. this._rotated.x += this._pivotBackTranslation.x;
  54787. this._rotated.y += this._pivotBackTranslation.y;
  54788. this._rotated.z += this._pivotBackTranslation.z;
  54789. 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;
  54790. 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;
  54791. 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;
  54792. if (this._computeBoundingBox) {
  54793. if (this._positions32[idx] < this._minimum.x) {
  54794. this._minimum.x = this._positions32[idx];
  54795. }
  54796. if (this._positions32[idx] > this._maximum.x) {
  54797. this._maximum.x = this._positions32[idx];
  54798. }
  54799. if (this._positions32[idx + 1] < this._minimum.y) {
  54800. this._minimum.y = this._positions32[idx + 1];
  54801. }
  54802. if (this._positions32[idx + 1] > this._maximum.y) {
  54803. this._maximum.y = this._positions32[idx + 1];
  54804. }
  54805. if (this._positions32[idx + 2] < this._minimum.z) {
  54806. this._minimum.z = this._positions32[idx + 2];
  54807. }
  54808. if (this._positions32[idx + 2] > this._maximum.z) {
  54809. this._maximum.z = this._positions32[idx + 2];
  54810. }
  54811. }
  54812. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54813. if (!this._computeParticleVertex) {
  54814. this._normal.x = this._fixedNormal32[idx];
  54815. this._normal.y = this._fixedNormal32[idx + 1];
  54816. this._normal.z = this._fixedNormal32[idx + 2];
  54817. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54818. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54819. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54820. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54821. 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;
  54822. 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;
  54823. }
  54824. if (this._computeParticleColor && this._particle.color) {
  54825. this._colors32[colidx] = this._particle.color.r;
  54826. this._colors32[colidx + 1] = this._particle.color.g;
  54827. this._colors32[colidx + 2] = this._particle.color.b;
  54828. this._colors32[colidx + 3] = this._particle.color.a;
  54829. }
  54830. if (this._computeParticleTexture) {
  54831. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54832. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54833. }
  54834. }
  54835. }
  54836. else {
  54837. this._particle._stillInvisible = true; // mark the particle as invisible
  54838. for (pt = 0; pt < this._shape.length; pt++) {
  54839. idx = index + pt * 3;
  54840. colidx = colorIndex + pt * 4;
  54841. uvidx = uvIndex + pt * 2;
  54842. this._positions32[idx] = 0.0;
  54843. this._positions32[idx + 1] = 0.0;
  54844. this._positions32[idx + 2] = 0.0;
  54845. this._normals32[idx] = 0.0;
  54846. this._normals32[idx + 1] = 0.0;
  54847. this._normals32[idx + 2] = 0.0;
  54848. if (this._computeParticleColor && this._particle.color) {
  54849. this._colors32[colidx] = this._particle.color.r;
  54850. this._colors32[colidx + 1] = this._particle.color.g;
  54851. this._colors32[colidx + 2] = this._particle.color.b;
  54852. this._colors32[colidx + 3] = this._particle.color.a;
  54853. }
  54854. if (this._computeParticleTexture) {
  54855. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54856. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54857. }
  54858. }
  54859. }
  54860. // if the particle intersections must be computed : update the bbInfo
  54861. if (this._particlesIntersect) {
  54862. var bInfo = this._particle._boundingInfo;
  54863. var bBox = bInfo.boundingBox;
  54864. var bSphere = bInfo.boundingSphere;
  54865. if (!this._bSphereOnly) {
  54866. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54867. for (var b = 0; b < bBox.vectors.length; b++) {
  54868. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54869. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54870. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54871. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54872. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54873. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54874. 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;
  54875. 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;
  54876. 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;
  54877. }
  54878. bBox._update(this.mesh._worldMatrix);
  54879. }
  54880. // place and scale the particle bouding sphere in the SPS local system, then update it
  54881. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54882. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54883. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54884. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54885. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54886. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54887. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54888. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54889. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54890. 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));
  54891. bSphere._update(this.mesh._worldMatrix);
  54892. }
  54893. // increment indexes for the next particle
  54894. index = idx + 3;
  54895. colorIndex = colidx + 4;
  54896. uvIndex = uvidx + 2;
  54897. }
  54898. // if the VBO must be updated
  54899. if (update) {
  54900. if (this._computeParticleColor) {
  54901. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54902. }
  54903. if (this._computeParticleTexture) {
  54904. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54905. }
  54906. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54907. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54908. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54909. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54910. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54911. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54912. for (var i = 0; i < this._normals32.length; i++) {
  54913. this._fixedNormal32[i] = this._normals32[i];
  54914. }
  54915. }
  54916. if (!this.mesh.areNormalsFrozen) {
  54917. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54918. }
  54919. }
  54920. if (this._depthSort && this._depthSortParticles) {
  54921. this.depthSortedParticles.sort(this._depthSortFunction);
  54922. var dspl = this.depthSortedParticles.length;
  54923. var sorted = 0;
  54924. var lind = 0;
  54925. var sind = 0;
  54926. var sid = 0;
  54927. for (sorted = 0; sorted < dspl; sorted++) {
  54928. lind = this.depthSortedParticles[sorted].indicesLength;
  54929. sind = this.depthSortedParticles[sorted].ind;
  54930. for (var i = 0; i < lind; i++) {
  54931. this._indices32[sid] = this._indices[sind + i];
  54932. sid++;
  54933. }
  54934. }
  54935. this.mesh.updateIndices(this._indices32);
  54936. }
  54937. }
  54938. if (this._computeBoundingBox) {
  54939. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54940. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54941. }
  54942. this.afterUpdateParticles(start, end, update);
  54943. return this;
  54944. };
  54945. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54946. this._halfroll = this._roll * 0.5;
  54947. this._halfpitch = this._pitch * 0.5;
  54948. this._halfyaw = this._yaw * 0.5;
  54949. this._sinRoll = Math.sin(this._halfroll);
  54950. this._cosRoll = Math.cos(this._halfroll);
  54951. this._sinPitch = Math.sin(this._halfpitch);
  54952. this._cosPitch = Math.cos(this._halfpitch);
  54953. this._sinYaw = Math.sin(this._halfyaw);
  54954. this._cosYaw = Math.cos(this._halfyaw);
  54955. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54956. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54957. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54958. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54959. };
  54960. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54961. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54962. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54963. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54964. this._rotMatrix.m[3] = 0;
  54965. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54966. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54967. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54968. this._rotMatrix.m[7] = 0;
  54969. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54970. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54971. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54972. this._rotMatrix.m[11] = 0;
  54973. this._rotMatrix.m[12] = 0;
  54974. this._rotMatrix.m[13] = 0;
  54975. this._rotMatrix.m[14] = 0;
  54976. this._rotMatrix.m[15] = 1.0;
  54977. };
  54978. /**
  54979. * Disposes the SPS.
  54980. */
  54981. SolidParticleSystem.prototype.dispose = function () {
  54982. this.mesh.dispose();
  54983. this.vars = null;
  54984. // drop references to internal big arrays for the GC
  54985. this._positions = null;
  54986. this._indices = null;
  54987. this._normals = null;
  54988. this._uvs = null;
  54989. this._colors = null;
  54990. this._indices32 = null;
  54991. this._positions32 = null;
  54992. this._normals32 = null;
  54993. this._fixedNormal32 = null;
  54994. this._uvs32 = null;
  54995. this._colors32 = null;
  54996. this.pickedParticles = null;
  54997. };
  54998. /**
  54999. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  55000. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55001. * @returns the SPS.
  55002. */
  55003. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  55004. if (!this._isVisibilityBoxLocked) {
  55005. this.mesh.refreshBoundingInfo();
  55006. }
  55007. return this;
  55008. };
  55009. /**
  55010. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  55011. * @param size the size (float) of the visibility box
  55012. * note : this doesn't lock the SPS mesh bounding box.
  55013. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55014. */
  55015. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  55016. var vis = size / 2;
  55017. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  55018. };
  55019. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  55020. /**
  55021. * Gets whether the SPS as always visible or not
  55022. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55023. */
  55024. get: function () {
  55025. return this._alwaysVisible;
  55026. },
  55027. /**
  55028. * Sets the SPS as always visible or not
  55029. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55030. */
  55031. set: function (val) {
  55032. this._alwaysVisible = val;
  55033. this.mesh.alwaysSelectAsActiveMesh = val;
  55034. },
  55035. enumerable: true,
  55036. configurable: true
  55037. });
  55038. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  55039. /**
  55040. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55041. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55042. */
  55043. get: function () {
  55044. return this._isVisibilityBoxLocked;
  55045. },
  55046. /**
  55047. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  55048. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  55049. */
  55050. set: function (val) {
  55051. this._isVisibilityBoxLocked = val;
  55052. var boundingInfo = this.mesh.getBoundingInfo();
  55053. boundingInfo.isLocked = val;
  55054. },
  55055. enumerable: true,
  55056. configurable: true
  55057. });
  55058. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  55059. /**
  55060. * Gets if `setParticles()` computes the particle rotations or not.
  55061. * Default value : true. The SPS is faster when it's set to false.
  55062. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55063. */
  55064. get: function () {
  55065. return this._computeParticleRotation;
  55066. },
  55067. /**
  55068. * Tells to `setParticles()` to compute the particle rotations or not.
  55069. * Default value : true. The SPS is faster when it's set to false.
  55070. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  55071. */
  55072. set: function (val) {
  55073. this._computeParticleRotation = val;
  55074. },
  55075. enumerable: true,
  55076. configurable: true
  55077. });
  55078. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  55079. /**
  55080. * Gets if `setParticles()` computes the particle colors or not.
  55081. * Default value : true. The SPS is faster when it's set to false.
  55082. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55083. */
  55084. get: function () {
  55085. return this._computeParticleColor;
  55086. },
  55087. /**
  55088. * Tells to `setParticles()` to compute the particle colors or not.
  55089. * Default value : true. The SPS is faster when it's set to false.
  55090. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  55091. */
  55092. set: function (val) {
  55093. this._computeParticleColor = val;
  55094. },
  55095. enumerable: true,
  55096. configurable: true
  55097. });
  55098. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  55099. /**
  55100. * Gets if `setParticles()` computes the particle textures or not.
  55101. * Default value : true. The SPS is faster when it's set to false.
  55102. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  55103. */
  55104. get: function () {
  55105. return this._computeParticleTexture;
  55106. },
  55107. set: function (val) {
  55108. this._computeParticleTexture = val;
  55109. },
  55110. enumerable: true,
  55111. configurable: true
  55112. });
  55113. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  55114. /**
  55115. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  55116. * Default value : false. The SPS is faster when it's set to false.
  55117. * Note : the particle custom vertex positions aren't stored values.
  55118. */
  55119. get: function () {
  55120. return this._computeParticleVertex;
  55121. },
  55122. /**
  55123. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  55124. * Default value : false. The SPS is faster when it's set to false.
  55125. * Note : the particle custom vertex positions aren't stored values.
  55126. */
  55127. set: function (val) {
  55128. this._computeParticleVertex = val;
  55129. },
  55130. enumerable: true,
  55131. configurable: true
  55132. });
  55133. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  55134. /**
  55135. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  55136. */
  55137. get: function () {
  55138. return this._computeBoundingBox;
  55139. },
  55140. /**
  55141. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  55142. */
  55143. set: function (val) {
  55144. this._computeBoundingBox = val;
  55145. },
  55146. enumerable: true,
  55147. configurable: true
  55148. });
  55149. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  55150. /**
  55151. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  55152. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55153. * Default : `true`
  55154. */
  55155. get: function () {
  55156. return this._depthSortParticles;
  55157. },
  55158. /**
  55159. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  55160. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  55161. * Default : `true`
  55162. */
  55163. set: function (val) {
  55164. this._depthSortParticles = val;
  55165. },
  55166. enumerable: true,
  55167. configurable: true
  55168. });
  55169. // =======================================================================
  55170. // Particle behavior logic
  55171. // these following methods may be overwritten by the user to fit his needs
  55172. /**
  55173. * This function does nothing. It may be overwritten to set all the particle first values.
  55174. * The SPS doesn't call this function, you may have to call it by your own.
  55175. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55176. */
  55177. SolidParticleSystem.prototype.initParticles = function () {
  55178. };
  55179. /**
  55180. * This function does nothing. It may be overwritten to recycle a particle.
  55181. * The SPS doesn't call this function, you may have to call it by your own.
  55182. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55183. * @param particle The particle to recycle
  55184. * @returns the recycled particle
  55185. */
  55186. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  55187. return particle;
  55188. };
  55189. /**
  55190. * Updates a particle : this function should be overwritten by the user.
  55191. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  55192. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  55193. * @example : just set a particle position or velocity and recycle conditions
  55194. * @param particle The particle to update
  55195. * @returns the updated particle
  55196. */
  55197. SolidParticleSystem.prototype.updateParticle = function (particle) {
  55198. return particle;
  55199. };
  55200. /**
  55201. * Updates a vertex of a particle : it can be overwritten by the user.
  55202. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  55203. * @param particle the current particle
  55204. * @param vertex the current index of the current particle
  55205. * @param pt the index of the current vertex in the particle shape
  55206. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  55207. * @example : just set a vertex particle position
  55208. * @returns the updated vertex
  55209. */
  55210. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  55211. return vertex;
  55212. };
  55213. /**
  55214. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  55215. * This does nothing and may be overwritten by the user.
  55216. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55217. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55218. * @param update the boolean update value actually passed to setParticles()
  55219. */
  55220. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  55221. };
  55222. /**
  55223. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55224. * This will be passed three parameters.
  55225. * This does nothing and may be overwritten by the user.
  55226. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55227. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55228. * @param update the boolean update value actually passed to setParticles()
  55229. */
  55230. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55231. };
  55232. return SolidParticleSystem;
  55233. }());
  55234. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55235. })(BABYLON || (BABYLON = {}));
  55236. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55237. "use strict";
  55238. var BABYLON;
  55239. (function (BABYLON) {
  55240. var ShaderMaterial = /** @class */ (function (_super) {
  55241. __extends(ShaderMaterial, _super);
  55242. function ShaderMaterial(name, scene, shaderPath, options) {
  55243. var _this = _super.call(this, name, scene) || this;
  55244. _this._textures = {};
  55245. _this._textureArrays = {};
  55246. _this._floats = {};
  55247. _this._ints = {};
  55248. _this._floatsArrays = {};
  55249. _this._colors3 = {};
  55250. _this._colors3Arrays = {};
  55251. _this._colors4 = {};
  55252. _this._vectors2 = {};
  55253. _this._vectors3 = {};
  55254. _this._vectors4 = {};
  55255. _this._matrices = {};
  55256. _this._matrices3x3 = {};
  55257. _this._matrices2x2 = {};
  55258. _this._vectors2Arrays = {};
  55259. _this._vectors3Arrays = {};
  55260. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55261. _this._shaderPath = shaderPath;
  55262. options.needAlphaBlending = options.needAlphaBlending || false;
  55263. options.needAlphaTesting = options.needAlphaTesting || false;
  55264. options.attributes = options.attributes || ["position", "normal", "uv"];
  55265. options.uniforms = options.uniforms || ["worldViewProjection"];
  55266. options.uniformBuffers = options.uniformBuffers || [];
  55267. options.samplers = options.samplers || [];
  55268. options.defines = options.defines || [];
  55269. _this._options = options;
  55270. return _this;
  55271. }
  55272. ShaderMaterial.prototype.getClassName = function () {
  55273. return "ShaderMaterial";
  55274. };
  55275. ShaderMaterial.prototype.needAlphaBlending = function () {
  55276. return this._options.needAlphaBlending;
  55277. };
  55278. ShaderMaterial.prototype.needAlphaTesting = function () {
  55279. return this._options.needAlphaTesting;
  55280. };
  55281. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55282. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55283. this._options.uniforms.push(uniformName);
  55284. }
  55285. };
  55286. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55287. if (this._options.samplers.indexOf(name) === -1) {
  55288. this._options.samplers.push(name);
  55289. }
  55290. this._textures[name] = texture;
  55291. return this;
  55292. };
  55293. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55294. if (this._options.samplers.indexOf(name) === -1) {
  55295. this._options.samplers.push(name);
  55296. }
  55297. this._checkUniform(name);
  55298. this._textureArrays[name] = textures;
  55299. return this;
  55300. };
  55301. ShaderMaterial.prototype.setFloat = function (name, value) {
  55302. this._checkUniform(name);
  55303. this._floats[name] = value;
  55304. return this;
  55305. };
  55306. ShaderMaterial.prototype.setInt = function (name, value) {
  55307. this._checkUniform(name);
  55308. this._ints[name] = value;
  55309. return this;
  55310. };
  55311. ShaderMaterial.prototype.setFloats = function (name, value) {
  55312. this._checkUniform(name);
  55313. this._floatsArrays[name] = value;
  55314. return this;
  55315. };
  55316. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55317. this._checkUniform(name);
  55318. this._colors3[name] = value;
  55319. return this;
  55320. };
  55321. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55322. this._checkUniform(name);
  55323. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55324. color.toArray(arr, arr.length);
  55325. return arr;
  55326. }, []);
  55327. return this;
  55328. };
  55329. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55330. this._checkUniform(name);
  55331. this._colors4[name] = value;
  55332. return this;
  55333. };
  55334. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55335. this._checkUniform(name);
  55336. this._vectors2[name] = value;
  55337. return this;
  55338. };
  55339. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55340. this._checkUniform(name);
  55341. this._vectors3[name] = value;
  55342. return this;
  55343. };
  55344. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55345. this._checkUniform(name);
  55346. this._vectors4[name] = value;
  55347. return this;
  55348. };
  55349. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55350. this._checkUniform(name);
  55351. this._matrices[name] = value;
  55352. return this;
  55353. };
  55354. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55355. this._checkUniform(name);
  55356. this._matrices3x3[name] = value;
  55357. return this;
  55358. };
  55359. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55360. this._checkUniform(name);
  55361. this._matrices2x2[name] = value;
  55362. return this;
  55363. };
  55364. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55365. this._checkUniform(name);
  55366. this._vectors2Arrays[name] = value;
  55367. return this;
  55368. };
  55369. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55370. this._checkUniform(name);
  55371. this._vectors3Arrays[name] = value;
  55372. return this;
  55373. };
  55374. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55375. if (!mesh) {
  55376. return true;
  55377. }
  55378. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55379. return false;
  55380. }
  55381. return false;
  55382. };
  55383. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55384. var scene = this.getScene();
  55385. var engine = scene.getEngine();
  55386. if (!this.checkReadyOnEveryCall) {
  55387. if (this._renderId === scene.getRenderId()) {
  55388. if (this._checkCache(scene, mesh, useInstances)) {
  55389. return true;
  55390. }
  55391. }
  55392. }
  55393. // Instances
  55394. var defines = [];
  55395. var attribs = [];
  55396. var fallbacks = new BABYLON.EffectFallbacks();
  55397. if (useInstances) {
  55398. defines.push("#define INSTANCES");
  55399. }
  55400. for (var index = 0; index < this._options.defines.length; index++) {
  55401. defines.push(this._options.defines[index]);
  55402. }
  55403. for (var index = 0; index < this._options.attributes.length; index++) {
  55404. attribs.push(this._options.attributes[index]);
  55405. }
  55406. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55407. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55408. defines.push("#define VERTEXCOLOR");
  55409. }
  55410. // Bones
  55411. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55412. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55413. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55414. if (mesh.numBoneInfluencers > 4) {
  55415. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55416. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55417. }
  55418. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55419. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55420. fallbacks.addCPUSkinningFallback(0, mesh);
  55421. if (this._options.uniforms.indexOf("mBones") === -1) {
  55422. this._options.uniforms.push("mBones");
  55423. }
  55424. }
  55425. else {
  55426. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55427. }
  55428. // Textures
  55429. for (var name in this._textures) {
  55430. if (!this._textures[name].isReady()) {
  55431. return false;
  55432. }
  55433. }
  55434. // Alpha test
  55435. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55436. defines.push("#define ALPHATEST");
  55437. }
  55438. var previousEffect = this._effect;
  55439. var join = defines.join("\n");
  55440. this._effect = engine.createEffect(this._shaderPath, {
  55441. attributes: attribs,
  55442. uniformsNames: this._options.uniforms,
  55443. uniformBuffersNames: this._options.uniformBuffers,
  55444. samplers: this._options.samplers,
  55445. defines: join,
  55446. fallbacks: fallbacks,
  55447. onCompiled: this.onCompiled,
  55448. onError: this.onError
  55449. }, engine);
  55450. if (!this._effect.isReady()) {
  55451. return false;
  55452. }
  55453. if (previousEffect !== this._effect) {
  55454. scene.resetCachedMaterial();
  55455. }
  55456. this._renderId = scene.getRenderId();
  55457. return true;
  55458. };
  55459. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55460. var scene = this.getScene();
  55461. if (!this._effect) {
  55462. return;
  55463. }
  55464. if (this._options.uniforms.indexOf("world") !== -1) {
  55465. this._effect.setMatrix("world", world);
  55466. }
  55467. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55468. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55469. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55470. }
  55471. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55472. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55473. }
  55474. };
  55475. ShaderMaterial.prototype.bind = function (world, mesh) {
  55476. // Std values
  55477. this.bindOnlyWorldMatrix(world);
  55478. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55479. if (this._options.uniforms.indexOf("view") !== -1) {
  55480. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55481. }
  55482. if (this._options.uniforms.indexOf("projection") !== -1) {
  55483. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55484. }
  55485. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55486. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55487. }
  55488. // Bones
  55489. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55490. var name;
  55491. // Texture
  55492. for (name in this._textures) {
  55493. this._effect.setTexture(name, this._textures[name]);
  55494. }
  55495. // Texture arrays
  55496. for (name in this._textureArrays) {
  55497. this._effect.setTextureArray(name, this._textureArrays[name]);
  55498. }
  55499. // Int
  55500. for (name in this._ints) {
  55501. this._effect.setInt(name, this._ints[name]);
  55502. }
  55503. // Float
  55504. for (name in this._floats) {
  55505. this._effect.setFloat(name, this._floats[name]);
  55506. }
  55507. // Floats
  55508. for (name in this._floatsArrays) {
  55509. this._effect.setArray(name, this._floatsArrays[name]);
  55510. }
  55511. // Color3
  55512. for (name in this._colors3) {
  55513. this._effect.setColor3(name, this._colors3[name]);
  55514. }
  55515. for (name in this._colors3Arrays) {
  55516. this._effect.setArray3(name, this._colors3Arrays[name]);
  55517. }
  55518. // Color4
  55519. for (name in this._colors4) {
  55520. var color = this._colors4[name];
  55521. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55522. }
  55523. // Vector2
  55524. for (name in this._vectors2) {
  55525. this._effect.setVector2(name, this._vectors2[name]);
  55526. }
  55527. // Vector3
  55528. for (name in this._vectors3) {
  55529. this._effect.setVector3(name, this._vectors3[name]);
  55530. }
  55531. // Vector4
  55532. for (name in this._vectors4) {
  55533. this._effect.setVector4(name, this._vectors4[name]);
  55534. }
  55535. // Matrix
  55536. for (name in this._matrices) {
  55537. this._effect.setMatrix(name, this._matrices[name]);
  55538. }
  55539. // Matrix 3x3
  55540. for (name in this._matrices3x3) {
  55541. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55542. }
  55543. // Matrix 2x2
  55544. for (name in this._matrices2x2) {
  55545. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55546. }
  55547. // Vector2Array
  55548. for (name in this._vectors2Arrays) {
  55549. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55550. }
  55551. // Vector3Array
  55552. for (name in this._vectors3Arrays) {
  55553. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55554. }
  55555. }
  55556. this._afterBind(mesh);
  55557. };
  55558. ShaderMaterial.prototype.getActiveTextures = function () {
  55559. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55560. for (var name in this._textures) {
  55561. activeTextures.push(this._textures[name]);
  55562. }
  55563. for (var name in this._textureArrays) {
  55564. var array = this._textureArrays[name];
  55565. for (var index = 0; index < array.length; index++) {
  55566. activeTextures.push(array[index]);
  55567. }
  55568. }
  55569. return activeTextures;
  55570. };
  55571. ShaderMaterial.prototype.hasTexture = function (texture) {
  55572. if (_super.prototype.hasTexture.call(this, texture)) {
  55573. return true;
  55574. }
  55575. for (var name in this._textures) {
  55576. if (this._textures[name] === texture) {
  55577. return true;
  55578. }
  55579. }
  55580. for (var name in this._textureArrays) {
  55581. var array = this._textureArrays[name];
  55582. for (var index = 0; index < array.length; index++) {
  55583. if (array[index] === texture) {
  55584. return true;
  55585. }
  55586. }
  55587. }
  55588. return false;
  55589. };
  55590. ShaderMaterial.prototype.clone = function (name) {
  55591. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55592. return newShaderMaterial;
  55593. };
  55594. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55595. if (forceDisposeTextures) {
  55596. var name;
  55597. for (name in this._textures) {
  55598. this._textures[name].dispose();
  55599. }
  55600. for (name in this._textureArrays) {
  55601. var array = this._textureArrays[name];
  55602. for (var index = 0; index < array.length; index++) {
  55603. array[index].dispose();
  55604. }
  55605. }
  55606. }
  55607. this._textures = {};
  55608. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55609. };
  55610. ShaderMaterial.prototype.serialize = function () {
  55611. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55612. serializationObject.customType = "BABYLON.ShaderMaterial";
  55613. serializationObject.options = this._options;
  55614. serializationObject.shaderPath = this._shaderPath;
  55615. var name;
  55616. // Texture
  55617. serializationObject.textures = {};
  55618. for (name in this._textures) {
  55619. serializationObject.textures[name] = this._textures[name].serialize();
  55620. }
  55621. // Texture arrays
  55622. serializationObject.textureArrays = {};
  55623. for (name in this._textureArrays) {
  55624. serializationObject.textureArrays[name] = [];
  55625. var array = this._textureArrays[name];
  55626. for (var index = 0; index < array.length; index++) {
  55627. serializationObject.textureArrays[name].push(array[index].serialize());
  55628. }
  55629. }
  55630. // Float
  55631. serializationObject.floats = {};
  55632. for (name in this._floats) {
  55633. serializationObject.floats[name] = this._floats[name];
  55634. }
  55635. // Float s
  55636. serializationObject.FloatArrays = {};
  55637. for (name in this._floatsArrays) {
  55638. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55639. }
  55640. // Color3
  55641. serializationObject.colors3 = {};
  55642. for (name in this._colors3) {
  55643. serializationObject.colors3[name] = this._colors3[name].asArray();
  55644. }
  55645. // Color3 array
  55646. serializationObject.colors3Arrays = {};
  55647. for (name in this._colors3Arrays) {
  55648. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55649. }
  55650. // Color4
  55651. serializationObject.colors4 = {};
  55652. for (name in this._colors4) {
  55653. serializationObject.colors4[name] = this._colors4[name].asArray();
  55654. }
  55655. // Vector2
  55656. serializationObject.vectors2 = {};
  55657. for (name in this._vectors2) {
  55658. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55659. }
  55660. // Vector3
  55661. serializationObject.vectors3 = {};
  55662. for (name in this._vectors3) {
  55663. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55664. }
  55665. // Vector4
  55666. serializationObject.vectors4 = {};
  55667. for (name in this._vectors4) {
  55668. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55669. }
  55670. // Matrix
  55671. serializationObject.matrices = {};
  55672. for (name in this._matrices) {
  55673. serializationObject.matrices[name] = this._matrices[name].asArray();
  55674. }
  55675. // Matrix 3x3
  55676. serializationObject.matrices3x3 = {};
  55677. for (name in this._matrices3x3) {
  55678. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55679. }
  55680. // Matrix 2x2
  55681. serializationObject.matrices2x2 = {};
  55682. for (name in this._matrices2x2) {
  55683. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55684. }
  55685. // Vector2Array
  55686. serializationObject.vectors2Arrays = {};
  55687. for (name in this._vectors2Arrays) {
  55688. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55689. }
  55690. // Vector3Array
  55691. serializationObject.vectors3Arrays = {};
  55692. for (name in this._vectors3Arrays) {
  55693. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55694. }
  55695. return serializationObject;
  55696. };
  55697. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55698. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55699. var name;
  55700. // Texture
  55701. for (name in source.textures) {
  55702. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55703. }
  55704. // Texture arrays
  55705. for (name in source.textureArrays) {
  55706. var array = source.textureArrays[name];
  55707. var textureArray = new Array();
  55708. for (var index = 0; index < array.length; index++) {
  55709. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55710. }
  55711. material.setTextureArray(name, textureArray);
  55712. }
  55713. // Float
  55714. for (name in source.floats) {
  55715. material.setFloat(name, source.floats[name]);
  55716. }
  55717. // Float s
  55718. for (name in source.floatsArrays) {
  55719. material.setFloats(name, source.floatsArrays[name]);
  55720. }
  55721. // Color3
  55722. for (name in source.colors3) {
  55723. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55724. }
  55725. // Color3 arrays
  55726. for (name in source.colors3Arrays) {
  55727. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55728. if (i % 3 === 0) {
  55729. arr.push([num]);
  55730. }
  55731. else {
  55732. arr[arr.length - 1].push(num);
  55733. }
  55734. return arr;
  55735. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55736. material.setColor3Array(name, colors);
  55737. }
  55738. // Color4
  55739. for (name in source.colors4) {
  55740. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55741. }
  55742. // Vector2
  55743. for (name in source.vectors2) {
  55744. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55745. }
  55746. // Vector3
  55747. for (name in source.vectors3) {
  55748. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55749. }
  55750. // Vector4
  55751. for (name in source.vectors4) {
  55752. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55753. }
  55754. // Matrix
  55755. for (name in source.matrices) {
  55756. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55757. }
  55758. // Matrix 3x3
  55759. for (name in source.matrices3x3) {
  55760. material.setMatrix3x3(name, source.matrices3x3[name]);
  55761. }
  55762. // Matrix 2x2
  55763. for (name in source.matrices2x2) {
  55764. material.setMatrix2x2(name, source.matrices2x2[name]);
  55765. }
  55766. // Vector2Array
  55767. for (name in source.vectors2Arrays) {
  55768. material.setArray2(name, source.vectors2Arrays[name]);
  55769. }
  55770. // Vector3Array
  55771. for (name in source.vectors3Arrays) {
  55772. material.setArray3(name, source.vectors3Arrays[name]);
  55773. }
  55774. return material;
  55775. };
  55776. return ShaderMaterial;
  55777. }(BABYLON.Material));
  55778. BABYLON.ShaderMaterial = ShaderMaterial;
  55779. })(BABYLON || (BABYLON = {}));
  55780. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55781. "use strict";
  55782. var BABYLON;
  55783. (function (BABYLON) {
  55784. var GroundMesh = /** @class */ (function (_super) {
  55785. __extends(GroundMesh, _super);
  55786. function GroundMesh(name, scene) {
  55787. var _this = _super.call(this, name, scene) || this;
  55788. _this.generateOctree = false;
  55789. return _this;
  55790. }
  55791. GroundMesh.prototype.getClassName = function () {
  55792. return "GroundMesh";
  55793. };
  55794. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55795. get: function () {
  55796. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55797. },
  55798. enumerable: true,
  55799. configurable: true
  55800. });
  55801. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55802. get: function () {
  55803. return this._subdivisionsX;
  55804. },
  55805. enumerable: true,
  55806. configurable: true
  55807. });
  55808. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55809. get: function () {
  55810. return this._subdivisionsY;
  55811. },
  55812. enumerable: true,
  55813. configurable: true
  55814. });
  55815. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55816. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55817. this._subdivisionsX = chunksCount;
  55818. this._subdivisionsY = chunksCount;
  55819. this.subdivide(chunksCount);
  55820. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55821. };
  55822. /**
  55823. * Returns a height (y) value in the Worl system :
  55824. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55825. * Returns the ground y position if (x, z) are outside the ground surface.
  55826. */
  55827. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55828. var world = this.getWorldMatrix();
  55829. var invMat = BABYLON.Tmp.Matrix[5];
  55830. world.invertToRef(invMat);
  55831. var tmpVect = BABYLON.Tmp.Vector3[8];
  55832. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55833. x = tmpVect.x;
  55834. z = tmpVect.z;
  55835. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55836. return this.position.y;
  55837. }
  55838. if (!this._heightQuads || this._heightQuads.length == 0) {
  55839. this._initHeightQuads();
  55840. this._computeHeightQuads();
  55841. }
  55842. var facet = this._getFacetAt(x, z);
  55843. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55844. // return y in the World system
  55845. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55846. return tmpVect.y;
  55847. };
  55848. /**
  55849. * Returns a normalized vector (Vector3) orthogonal to the ground
  55850. * at the ground coordinates (x, z) expressed in the World system.
  55851. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55852. */
  55853. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55854. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55855. this.getNormalAtCoordinatesToRef(x, z, normal);
  55856. return normal;
  55857. };
  55858. /**
  55859. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55860. * at the ground coordinates (x, z) expressed in the World system.
  55861. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55862. * Returns the GroundMesh.
  55863. */
  55864. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55865. var world = this.getWorldMatrix();
  55866. var tmpMat = BABYLON.Tmp.Matrix[5];
  55867. world.invertToRef(tmpMat);
  55868. var tmpVect = BABYLON.Tmp.Vector3[8];
  55869. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55870. x = tmpVect.x;
  55871. z = tmpVect.z;
  55872. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55873. return this;
  55874. }
  55875. if (!this._heightQuads || this._heightQuads.length == 0) {
  55876. this._initHeightQuads();
  55877. this._computeHeightQuads();
  55878. }
  55879. var facet = this._getFacetAt(x, z);
  55880. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55881. return this;
  55882. };
  55883. /**
  55884. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55885. * if the ground has been updated.
  55886. * This can be used in the render loop.
  55887. * Returns the GroundMesh.
  55888. */
  55889. GroundMesh.prototype.updateCoordinateHeights = function () {
  55890. if (!this._heightQuads || this._heightQuads.length == 0) {
  55891. this._initHeightQuads();
  55892. }
  55893. this._computeHeightQuads();
  55894. return this;
  55895. };
  55896. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55897. GroundMesh.prototype._getFacetAt = function (x, z) {
  55898. // retrieve col and row from x, z coordinates in the ground local system
  55899. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55900. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55901. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55902. var facet;
  55903. if (z < quad.slope.x * x + quad.slope.y) {
  55904. facet = quad.facet1;
  55905. }
  55906. else {
  55907. facet = quad.facet2;
  55908. }
  55909. return facet;
  55910. };
  55911. // Creates and populates the heightMap array with "facet" elements :
  55912. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55913. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55914. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55915. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55916. // Returns the GroundMesh.
  55917. GroundMesh.prototype._initHeightQuads = function () {
  55918. var subdivisionsX = this._subdivisionsX;
  55919. var subdivisionsY = this._subdivisionsY;
  55920. this._heightQuads = new Array();
  55921. for (var row = 0; row < subdivisionsY; row++) {
  55922. for (var col = 0; col < subdivisionsX; col++) {
  55923. 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) };
  55924. this._heightQuads[row * subdivisionsX + col] = quad;
  55925. }
  55926. }
  55927. return this;
  55928. };
  55929. // Compute each quad element values and update the the heightMap array :
  55930. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55931. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55932. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55933. // Returns the GroundMesh.
  55934. GroundMesh.prototype._computeHeightQuads = function () {
  55935. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55936. if (!positions) {
  55937. return this;
  55938. }
  55939. var v1 = BABYLON.Tmp.Vector3[3];
  55940. var v2 = BABYLON.Tmp.Vector3[2];
  55941. var v3 = BABYLON.Tmp.Vector3[1];
  55942. var v4 = BABYLON.Tmp.Vector3[0];
  55943. var v1v2 = BABYLON.Tmp.Vector3[4];
  55944. var v1v3 = BABYLON.Tmp.Vector3[5];
  55945. var v1v4 = BABYLON.Tmp.Vector3[6];
  55946. var norm1 = BABYLON.Tmp.Vector3[7];
  55947. var norm2 = BABYLON.Tmp.Vector3[8];
  55948. var i = 0;
  55949. var j = 0;
  55950. var k = 0;
  55951. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55952. var h = 0;
  55953. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55954. var d2 = 0;
  55955. var subdivisionsX = this._subdivisionsX;
  55956. var subdivisionsY = this._subdivisionsY;
  55957. for (var row = 0; row < subdivisionsY; row++) {
  55958. for (var col = 0; col < subdivisionsX; col++) {
  55959. i = col * 3;
  55960. j = row * (subdivisionsX + 1) * 3;
  55961. k = (row + 1) * (subdivisionsX + 1) * 3;
  55962. v1.x = positions[j + i];
  55963. v1.y = positions[j + i + 1];
  55964. v1.z = positions[j + i + 2];
  55965. v2.x = positions[j + i + 3];
  55966. v2.y = positions[j + i + 4];
  55967. v2.z = positions[j + i + 5];
  55968. v3.x = positions[k + i];
  55969. v3.y = positions[k + i + 1];
  55970. v3.z = positions[k + i + 2];
  55971. v4.x = positions[k + i + 3];
  55972. v4.y = positions[k + i + 4];
  55973. v4.z = positions[k + i + 5];
  55974. // 2D slope V1V4
  55975. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55976. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55977. // facet equations :
  55978. // we compute each facet normal vector
  55979. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55980. // we compute the value d by applying the equation to v1 which belongs to the plane
  55981. // then we store the facet equation in a Vector4
  55982. v2.subtractToRef(v1, v1v2);
  55983. v3.subtractToRef(v1, v1v3);
  55984. v4.subtractToRef(v1, v1v4);
  55985. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55986. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55987. norm1.normalize();
  55988. norm2.normalize();
  55989. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55990. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55991. var quad = this._heightQuads[row * subdivisionsX + col];
  55992. quad.slope.copyFromFloats(cd, h);
  55993. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55994. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55995. }
  55996. }
  55997. return this;
  55998. };
  55999. GroundMesh.prototype.serialize = function (serializationObject) {
  56000. _super.prototype.serialize.call(this, serializationObject);
  56001. serializationObject.subdivisionsX = this._subdivisionsX;
  56002. serializationObject.subdivisionsY = this._subdivisionsY;
  56003. serializationObject.minX = this._minX;
  56004. serializationObject.maxX = this._maxX;
  56005. serializationObject.minZ = this._minZ;
  56006. serializationObject.maxZ = this._maxZ;
  56007. serializationObject.width = this._width;
  56008. serializationObject.height = this._height;
  56009. };
  56010. GroundMesh.Parse = function (parsedMesh, scene) {
  56011. var result = new GroundMesh(parsedMesh.name, scene);
  56012. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  56013. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  56014. result._minX = parsedMesh.minX;
  56015. result._maxX = parsedMesh.maxX;
  56016. result._minZ = parsedMesh.minZ;
  56017. result._maxZ = parsedMesh.maxZ;
  56018. result._width = parsedMesh.width;
  56019. result._height = parsedMesh.height;
  56020. return result;
  56021. };
  56022. return GroundMesh;
  56023. }(BABYLON.Mesh));
  56024. BABYLON.GroundMesh = GroundMesh;
  56025. })(BABYLON || (BABYLON = {}));
  56026. //# sourceMappingURL=babylon.groundMesh.js.map
  56027. "use strict";
  56028. var BABYLON;
  56029. (function (BABYLON) {
  56030. /**
  56031. * Creates an instance based on a source mesh.
  56032. */
  56033. var InstancedMesh = /** @class */ (function (_super) {
  56034. __extends(InstancedMesh, _super);
  56035. function InstancedMesh(name, source) {
  56036. var _this = _super.call(this, name, source.getScene()) || this;
  56037. source.instances.push(_this);
  56038. _this._sourceMesh = source;
  56039. _this.position.copyFrom(source.position);
  56040. _this.rotation.copyFrom(source.rotation);
  56041. _this.scaling.copyFrom(source.scaling);
  56042. if (source.rotationQuaternion) {
  56043. _this.rotationQuaternion = source.rotationQuaternion.clone();
  56044. }
  56045. _this.infiniteDistance = source.infiniteDistance;
  56046. _this.setPivotMatrix(source.getPivotMatrix());
  56047. _this.refreshBoundingInfo();
  56048. _this._syncSubMeshes();
  56049. return _this;
  56050. }
  56051. /**
  56052. * Returns the string "InstancedMesh".
  56053. */
  56054. InstancedMesh.prototype.getClassName = function () {
  56055. return "InstancedMesh";
  56056. };
  56057. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  56058. // Methods
  56059. get: function () {
  56060. return this._sourceMesh.receiveShadows;
  56061. },
  56062. enumerable: true,
  56063. configurable: true
  56064. });
  56065. Object.defineProperty(InstancedMesh.prototype, "material", {
  56066. get: function () {
  56067. return this._sourceMesh.material;
  56068. },
  56069. enumerable: true,
  56070. configurable: true
  56071. });
  56072. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  56073. get: function () {
  56074. return this._sourceMesh.visibility;
  56075. },
  56076. enumerable: true,
  56077. configurable: true
  56078. });
  56079. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  56080. get: function () {
  56081. return this._sourceMesh.skeleton;
  56082. },
  56083. enumerable: true,
  56084. configurable: true
  56085. });
  56086. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  56087. get: function () {
  56088. return this._sourceMesh.renderingGroupId;
  56089. },
  56090. set: function (value) {
  56091. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  56092. return;
  56093. }
  56094. //no-op with warning
  56095. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  56096. },
  56097. enumerable: true,
  56098. configurable: true
  56099. });
  56100. /**
  56101. * Returns the total number of vertices (integer).
  56102. */
  56103. InstancedMesh.prototype.getTotalVertices = function () {
  56104. return this._sourceMesh.getTotalVertices();
  56105. };
  56106. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  56107. get: function () {
  56108. return this._sourceMesh;
  56109. },
  56110. enumerable: true,
  56111. configurable: true
  56112. });
  56113. /**
  56114. * Is this node ready to be used/rendered
  56115. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  56116. * @return {boolean} is it ready
  56117. */
  56118. InstancedMesh.prototype.isReady = function (completeCheck) {
  56119. if (completeCheck === void 0) { completeCheck = false; }
  56120. return this._sourceMesh.isReady(completeCheck, true);
  56121. };
  56122. /**
  56123. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  56124. */
  56125. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  56126. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  56127. };
  56128. /**
  56129. * Sets the vertex data of the mesh geometry for the requested `kind`.
  56130. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  56131. * The `data` are either a numeric array either a Float32Array.
  56132. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  56133. * 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).
  56134. * Note that a new underlying VertexBuffer object is created each call.
  56135. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  56136. *
  56137. * Possible `kind` values :
  56138. * - BABYLON.VertexBuffer.PositionKind
  56139. * - BABYLON.VertexBuffer.UVKind
  56140. * - BABYLON.VertexBuffer.UV2Kind
  56141. * - BABYLON.VertexBuffer.UV3Kind
  56142. * - BABYLON.VertexBuffer.UV4Kind
  56143. * - BABYLON.VertexBuffer.UV5Kind
  56144. * - BABYLON.VertexBuffer.UV6Kind
  56145. * - BABYLON.VertexBuffer.ColorKind
  56146. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56147. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56148. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56149. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56150. *
  56151. * Returns the Mesh.
  56152. */
  56153. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  56154. if (this.sourceMesh) {
  56155. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  56156. }
  56157. return this.sourceMesh;
  56158. };
  56159. /**
  56160. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  56161. * If the mesh has no geometry, it is simply returned as it is.
  56162. * The `data` are either a numeric array either a Float32Array.
  56163. * No new underlying VertexBuffer object is created.
  56164. * 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.
  56165. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  56166. *
  56167. * Possible `kind` values :
  56168. * - BABYLON.VertexBuffer.PositionKind
  56169. * - BABYLON.VertexBuffer.UVKind
  56170. * - BABYLON.VertexBuffer.UV2Kind
  56171. * - BABYLON.VertexBuffer.UV3Kind
  56172. * - BABYLON.VertexBuffer.UV4Kind
  56173. * - BABYLON.VertexBuffer.UV5Kind
  56174. * - BABYLON.VertexBuffer.UV6Kind
  56175. * - BABYLON.VertexBuffer.ColorKind
  56176. * - BABYLON.VertexBuffer.MatricesIndicesKind
  56177. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  56178. * - BABYLON.VertexBuffer.MatricesWeightsKind
  56179. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  56180. *
  56181. * Returns the Mesh.
  56182. */
  56183. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  56184. if (this.sourceMesh) {
  56185. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  56186. }
  56187. return this.sourceMesh;
  56188. };
  56189. /**
  56190. * Sets the mesh indices.
  56191. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  56192. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  56193. * This method creates a new index buffer each call.
  56194. * Returns the Mesh.
  56195. */
  56196. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  56197. if (totalVertices === void 0) { totalVertices = null; }
  56198. if (this.sourceMesh) {
  56199. this.sourceMesh.setIndices(indices, totalVertices);
  56200. }
  56201. return this.sourceMesh;
  56202. };
  56203. /**
  56204. * Boolean : True if the mesh owns the requested kind of data.
  56205. */
  56206. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  56207. return this._sourceMesh.isVerticesDataPresent(kind);
  56208. };
  56209. /**
  56210. * Returns an array of indices (IndicesArray).
  56211. */
  56212. InstancedMesh.prototype.getIndices = function () {
  56213. return this._sourceMesh.getIndices();
  56214. };
  56215. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  56216. get: function () {
  56217. return this._sourceMesh._positions;
  56218. },
  56219. enumerable: true,
  56220. configurable: true
  56221. });
  56222. /**
  56223. * Sets a new updated BoundingInfo to the mesh.
  56224. * Returns the mesh.
  56225. */
  56226. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56227. var meshBB = this._sourceMesh.getBoundingInfo();
  56228. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56229. this._updateBoundingInfo();
  56230. return this;
  56231. };
  56232. InstancedMesh.prototype._preActivate = function () {
  56233. if (this._currentLOD) {
  56234. this._currentLOD._preActivate();
  56235. }
  56236. return this;
  56237. };
  56238. InstancedMesh.prototype._activate = function (renderId) {
  56239. if (this._currentLOD) {
  56240. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56241. }
  56242. return this;
  56243. };
  56244. /**
  56245. * Returns the current associated LOD AbstractMesh.
  56246. */
  56247. InstancedMesh.prototype.getLOD = function (camera) {
  56248. if (!camera) {
  56249. return this;
  56250. }
  56251. var boundingInfo = this.getBoundingInfo();
  56252. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56253. if (this._currentLOD === this.sourceMesh) {
  56254. return this;
  56255. }
  56256. return this._currentLOD;
  56257. };
  56258. InstancedMesh.prototype._syncSubMeshes = function () {
  56259. this.releaseSubMeshes();
  56260. if (this._sourceMesh.subMeshes) {
  56261. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56262. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56263. }
  56264. }
  56265. return this;
  56266. };
  56267. InstancedMesh.prototype._generatePointsArray = function () {
  56268. return this._sourceMesh._generatePointsArray();
  56269. };
  56270. /**
  56271. * Creates a new InstancedMesh from the current mesh.
  56272. * - name (string) : the cloned mesh name
  56273. * - newParent (optional Node) : the optional Node to parent the clone to.
  56274. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56275. *
  56276. * Returns the clone.
  56277. */
  56278. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56279. var result = this._sourceMesh.createInstance(name);
  56280. // Deep copy
  56281. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56282. // Bounding info
  56283. this.refreshBoundingInfo();
  56284. // Parent
  56285. if (newParent) {
  56286. result.parent = newParent;
  56287. }
  56288. if (!doNotCloneChildren) {
  56289. // Children
  56290. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56291. var mesh = this.getScene().meshes[index];
  56292. if (mesh.parent === this) {
  56293. mesh.clone(mesh.name, result);
  56294. }
  56295. }
  56296. }
  56297. result.computeWorldMatrix(true);
  56298. return result;
  56299. };
  56300. /**
  56301. * Disposes the InstancedMesh.
  56302. * Returns nothing.
  56303. */
  56304. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56305. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56306. // Remove from mesh
  56307. var index = this._sourceMesh.instances.indexOf(this);
  56308. this._sourceMesh.instances.splice(index, 1);
  56309. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56310. };
  56311. return InstancedMesh;
  56312. }(BABYLON.AbstractMesh));
  56313. BABYLON.InstancedMesh = InstancedMesh;
  56314. })(BABYLON || (BABYLON = {}));
  56315. //# sourceMappingURL=babylon.instancedMesh.js.map
  56316. "use strict";
  56317. var BABYLON;
  56318. (function (BABYLON) {
  56319. var LinesMesh = /** @class */ (function (_super) {
  56320. __extends(LinesMesh, _super);
  56321. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56322. if (scene === void 0) { scene = null; }
  56323. if (parent === void 0) { parent = null; }
  56324. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56325. _this.useVertexColor = useVertexColor;
  56326. _this.useVertexAlpha = useVertexAlpha;
  56327. _this.color = new BABYLON.Color3(1, 1, 1);
  56328. _this.alpha = 1;
  56329. if (source) {
  56330. _this.color = source.color.clone();
  56331. _this.alpha = source.alpha;
  56332. _this.useVertexColor = source.useVertexColor;
  56333. _this.useVertexAlpha = source.useVertexAlpha;
  56334. }
  56335. _this._intersectionThreshold = 0.1;
  56336. var defines = [];
  56337. var options = {
  56338. attributes: [BABYLON.VertexBuffer.PositionKind],
  56339. uniforms: ["world", "viewProjection"],
  56340. needAlphaBlending: true,
  56341. defines: defines
  56342. };
  56343. if (useVertexAlpha === false) {
  56344. options.needAlphaBlending = false;
  56345. }
  56346. if (!useVertexColor) {
  56347. options.uniforms.push("color");
  56348. }
  56349. else {
  56350. options.defines.push("#define VERTEXCOLOR");
  56351. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56352. }
  56353. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56354. return _this;
  56355. }
  56356. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56357. /**
  56358. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56359. * This margin is expressed in world space coordinates, so its value may vary.
  56360. * Default value is 0.1
  56361. * @returns the intersection Threshold value.
  56362. */
  56363. get: function () {
  56364. return this._intersectionThreshold;
  56365. },
  56366. /**
  56367. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56368. * This margin is expressed in world space coordinates, so its value may vary.
  56369. * @param value the new threshold to apply
  56370. */
  56371. set: function (value) {
  56372. if (this._intersectionThreshold === value) {
  56373. return;
  56374. }
  56375. this._intersectionThreshold = value;
  56376. if (this.geometry) {
  56377. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56378. }
  56379. },
  56380. enumerable: true,
  56381. configurable: true
  56382. });
  56383. /**
  56384. * Returns the string "LineMesh"
  56385. */
  56386. LinesMesh.prototype.getClassName = function () {
  56387. return "LinesMesh";
  56388. };
  56389. Object.defineProperty(LinesMesh.prototype, "material", {
  56390. get: function () {
  56391. return this._colorShader;
  56392. },
  56393. set: function (value) {
  56394. // Do nothing
  56395. },
  56396. enumerable: true,
  56397. configurable: true
  56398. });
  56399. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56400. get: function () {
  56401. return false;
  56402. },
  56403. enumerable: true,
  56404. configurable: true
  56405. });
  56406. LinesMesh.prototype.createInstance = function (name) {
  56407. throw new Error("LinesMeshes do not support createInstance.");
  56408. };
  56409. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56410. if (!this._geometry) {
  56411. return this;
  56412. }
  56413. // VBOs
  56414. this._geometry._bind(this._colorShader.getEffect());
  56415. // Color
  56416. if (!this.useVertexColor) {
  56417. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56418. }
  56419. return this;
  56420. };
  56421. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56422. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56423. return this;
  56424. }
  56425. var engine = this.getScene().getEngine();
  56426. // Draw order
  56427. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56428. return this;
  56429. };
  56430. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56431. this._colorShader.dispose();
  56432. _super.prototype.dispose.call(this, doNotRecurse);
  56433. };
  56434. /**
  56435. * Returns a new LineMesh object cloned from the current one.
  56436. */
  56437. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56438. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56439. };
  56440. return LinesMesh;
  56441. }(BABYLON.Mesh));
  56442. BABYLON.LinesMesh = LinesMesh;
  56443. })(BABYLON || (BABYLON = {}));
  56444. //# sourceMappingURL=babylon.linesMesh.js.map
  56445. "use strict";
  56446. var BABYLON;
  56447. (function (BABYLON) {
  56448. var MeshBuilder = /** @class */ (function () {
  56449. function MeshBuilder() {
  56450. }
  56451. MeshBuilder.updateSideOrientation = function (orientation) {
  56452. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56453. return BABYLON.Mesh.DOUBLESIDE;
  56454. }
  56455. if (orientation === undefined || orientation === null) {
  56456. return BABYLON.Mesh.FRONTSIDE;
  56457. }
  56458. return orientation;
  56459. };
  56460. /**
  56461. * Creates a box mesh.
  56462. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56463. * The parameter `size` sets the size (float) of each box side (default 1).
  56464. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56465. * 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).
  56466. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56467. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56468. * 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).
  56469. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56470. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56471. */
  56472. MeshBuilder.CreateBox = function (name, options, scene) {
  56473. if (scene === void 0) { scene = null; }
  56474. var box = new BABYLON.Mesh(name, scene);
  56475. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56476. box._originalBuilderSideOrientation = options.sideOrientation;
  56477. var vertexData = BABYLON.VertexData.CreateBox(options);
  56478. vertexData.applyToMesh(box, options.updatable);
  56479. return box;
  56480. };
  56481. /**
  56482. * Creates a sphere mesh.
  56483. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56484. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56485. * 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`).
  56486. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56487. * 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
  56488. * 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).
  56489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56490. * 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).
  56491. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56493. */
  56494. MeshBuilder.CreateSphere = function (name, options, scene) {
  56495. var sphere = new BABYLON.Mesh(name, scene);
  56496. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56497. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56498. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56499. vertexData.applyToMesh(sphere, options.updatable);
  56500. return sphere;
  56501. };
  56502. /**
  56503. * Creates a plane polygonal mesh. By default, this is a disc.
  56504. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56505. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56506. * 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.
  56507. * 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
  56508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56509. * 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).
  56510. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56512. */
  56513. MeshBuilder.CreateDisc = function (name, options, scene) {
  56514. if (scene === void 0) { scene = null; }
  56515. var disc = new BABYLON.Mesh(name, scene);
  56516. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56517. disc._originalBuilderSideOrientation = options.sideOrientation;
  56518. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56519. vertexData.applyToMesh(disc, options.updatable);
  56520. return disc;
  56521. };
  56522. /**
  56523. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56524. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56525. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56526. * 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`).
  56527. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56528. * 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.
  56529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56530. * 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).
  56531. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56533. */
  56534. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56535. var sphere = new BABYLON.Mesh(name, scene);
  56536. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56537. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56538. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56539. vertexData.applyToMesh(sphere, options.updatable);
  56540. return sphere;
  56541. };
  56542. ;
  56543. /**
  56544. * Creates a ribbon mesh.
  56545. * 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.
  56546. *
  56547. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56548. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56549. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56550. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56551. * 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.
  56552. * 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.
  56553. * 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
  56554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56555. * 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).
  56556. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56557. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56558. * 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.
  56559. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56560. * 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
  56561. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56562. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56564. */
  56565. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56566. if (scene === void 0) { scene = null; }
  56567. var pathArray = options.pathArray;
  56568. var closeArray = options.closeArray;
  56569. var closePath = options.closePath;
  56570. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56571. var instance = options.instance;
  56572. var updatable = options.updatable;
  56573. if (instance) {
  56574. // positionFunction : ribbon case
  56575. // only pathArray and sideOrientation parameters are taken into account for positions update
  56576. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56577. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56578. var positionFunction = function (positions) {
  56579. var minlg = pathArray[0].length;
  56580. var i = 0;
  56581. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56582. for (var si = 1; si <= ns; si++) {
  56583. for (var p = 0; p < pathArray.length; p++) {
  56584. var path = pathArray[p];
  56585. var l = path.length;
  56586. minlg = (minlg < l) ? minlg : l;
  56587. var j = 0;
  56588. while (j < minlg) {
  56589. positions[i] = path[j].x;
  56590. positions[i + 1] = path[j].y;
  56591. positions[i + 2] = path[j].z;
  56592. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56593. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56594. }
  56595. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56596. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56597. }
  56598. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56599. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56600. }
  56601. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56602. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56603. }
  56604. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56605. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56606. }
  56607. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56608. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56609. }
  56610. j++;
  56611. i += 3;
  56612. }
  56613. if (instance._closePath) {
  56614. positions[i] = path[0].x;
  56615. positions[i + 1] = path[0].y;
  56616. positions[i + 2] = path[0].z;
  56617. i += 3;
  56618. }
  56619. }
  56620. }
  56621. };
  56622. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56623. positionFunction(positions);
  56624. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56625. instance._boundingInfo.update(instance._worldMatrix);
  56626. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56627. if (options.colors) {
  56628. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56629. for (var c = 0; c < options.colors.length; c++) {
  56630. colors[c * 4] = options.colors[c].r;
  56631. colors[c * 4 + 1] = options.colors[c].g;
  56632. colors[c * 4 + 2] = options.colors[c].b;
  56633. colors[c * 4 + 3] = options.colors[c].a;
  56634. }
  56635. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56636. }
  56637. if (options.uvs) {
  56638. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56639. for (var i = 0; i < options.uvs.length; i++) {
  56640. uvs[i * 2] = options.uvs[i].x;
  56641. uvs[i * 2 + 1] = options.uvs[i].y;
  56642. }
  56643. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56644. }
  56645. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56646. var indices = instance.getIndices();
  56647. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56648. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56649. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56650. if (instance._closePath) {
  56651. var indexFirst = 0;
  56652. var indexLast = 0;
  56653. for (var p = 0; p < pathArray.length; p++) {
  56654. indexFirst = instance._idx[p] * 3;
  56655. if (p + 1 < pathArray.length) {
  56656. indexLast = (instance._idx[p + 1] - 1) * 3;
  56657. }
  56658. else {
  56659. indexLast = normals.length - 3;
  56660. }
  56661. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56662. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56663. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56664. normals[indexLast] = normals[indexFirst];
  56665. normals[indexLast + 1] = normals[indexFirst + 1];
  56666. normals[indexLast + 2] = normals[indexFirst + 2];
  56667. }
  56668. }
  56669. if (!(instance.areNormalsFrozen)) {
  56670. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56671. }
  56672. }
  56673. return instance;
  56674. }
  56675. else {
  56676. var ribbon = new BABYLON.Mesh(name, scene);
  56677. ribbon._originalBuilderSideOrientation = sideOrientation;
  56678. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56679. if (closePath) {
  56680. ribbon._idx = vertexData._idx;
  56681. }
  56682. ribbon._closePath = closePath;
  56683. ribbon._closeArray = closeArray;
  56684. vertexData.applyToMesh(ribbon, updatable);
  56685. return ribbon;
  56686. }
  56687. };
  56688. /**
  56689. * Creates a cylinder or a cone mesh.
  56690. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56691. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56692. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56693. * 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.
  56694. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56695. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56696. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56697. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56698. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56699. * 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).
  56700. * 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
  56701. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56702. * 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
  56703. * 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.
  56704. * If `enclose` is false, a ring surface is one element.
  56705. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56706. * 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
  56707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56708. * 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).
  56709. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56711. */
  56712. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56713. var cylinder = new BABYLON.Mesh(name, scene);
  56714. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56715. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56716. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56717. vertexData.applyToMesh(cylinder, options.updatable);
  56718. return cylinder;
  56719. };
  56720. /**
  56721. * Creates a torus mesh.
  56722. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56723. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56724. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56725. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56727. * 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).
  56728. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56729. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56730. */
  56731. MeshBuilder.CreateTorus = function (name, options, scene) {
  56732. var torus = new BABYLON.Mesh(name, scene);
  56733. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56734. torus._originalBuilderSideOrientation = options.sideOrientation;
  56735. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56736. vertexData.applyToMesh(torus, options.updatable);
  56737. return torus;
  56738. };
  56739. /**
  56740. * Creates a torus knot mesh.
  56741. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56742. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56743. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56744. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56745. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56746. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56747. * 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).
  56748. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56750. */
  56751. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56752. var torusKnot = new BABYLON.Mesh(name, scene);
  56753. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56754. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56755. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56756. vertexData.applyToMesh(torusKnot, options.updatable);
  56757. return torusKnot;
  56758. };
  56759. /**
  56760. * Creates a line system mesh.
  56761. * A line system is a pool of many lines gathered in a single mesh.
  56762. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56763. * 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.
  56764. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56765. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56766. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56767. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56768. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56769. * 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
  56770. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56771. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56772. */
  56773. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56774. var instance = options.instance;
  56775. var lines = options.lines;
  56776. var colors = options.colors;
  56777. if (instance) {
  56778. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56779. var vertexColor;
  56780. var lineColors;
  56781. if (colors) {
  56782. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56783. }
  56784. var i = 0;
  56785. var c = 0;
  56786. for (var l = 0; l < lines.length; l++) {
  56787. var points = lines[l];
  56788. for (var p = 0; p < points.length; p++) {
  56789. positions[i] = points[p].x;
  56790. positions[i + 1] = points[p].y;
  56791. positions[i + 2] = points[p].z;
  56792. if (colors && vertexColor) {
  56793. lineColors = colors[l];
  56794. vertexColor[c] = lineColors[p].r;
  56795. vertexColor[c + 1] = lineColors[p].g;
  56796. vertexColor[c + 2] = lineColors[p].b;
  56797. vertexColor[c + 3] = lineColors[p].a;
  56798. c += 4;
  56799. }
  56800. i += 3;
  56801. }
  56802. }
  56803. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56804. if (colors && vertexColor) {
  56805. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56806. }
  56807. return instance;
  56808. }
  56809. // line system creation
  56810. var useVertexColor = (colors) ? true : false;
  56811. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56812. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56813. vertexData.applyToMesh(lineSystem, options.updatable);
  56814. return lineSystem;
  56815. };
  56816. /**
  56817. * Creates a line mesh.
  56818. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56819. * 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.
  56820. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56821. * The parameter `points` is an array successive Vector3.
  56822. * 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
  56823. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56824. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56825. * When updating an instance, remember that only point positions can change, not the number of points.
  56826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56827. */
  56828. MeshBuilder.CreateLines = function (name, options, scene) {
  56829. if (scene === void 0) { scene = null; }
  56830. var colors = (options.colors) ? [options.colors] : null;
  56831. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56832. return lines;
  56833. };
  56834. /**
  56835. * Creates a dashed line mesh.
  56836. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56837. * 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.
  56838. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56839. * The parameter `points` is an array successive Vector3.
  56840. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56841. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56842. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56843. * 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
  56844. * When updating an instance, remember that only point positions can change, not the number of points.
  56845. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56846. */
  56847. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56848. if (scene === void 0) { scene = null; }
  56849. var points = options.points;
  56850. var instance = options.instance;
  56851. var gapSize = options.gapSize || 1;
  56852. var dashSize = options.dashSize || 3;
  56853. if (instance) {
  56854. var positionFunction = function (positions) {
  56855. var curvect = BABYLON.Vector3.Zero();
  56856. var nbSeg = positions.length / 6;
  56857. var lg = 0;
  56858. var nb = 0;
  56859. var shft = 0;
  56860. var dashshft = 0;
  56861. var curshft = 0;
  56862. var p = 0;
  56863. var i = 0;
  56864. var j = 0;
  56865. for (i = 0; i < points.length - 1; i++) {
  56866. points[i + 1].subtractToRef(points[i], curvect);
  56867. lg += curvect.length();
  56868. }
  56869. shft = lg / nbSeg;
  56870. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56871. for (i = 0; i < points.length - 1; i++) {
  56872. points[i + 1].subtractToRef(points[i], curvect);
  56873. nb = Math.floor(curvect.length() / shft);
  56874. curvect.normalize();
  56875. j = 0;
  56876. while (j < nb && p < positions.length) {
  56877. curshft = shft * j;
  56878. positions[p] = points[i].x + curshft * curvect.x;
  56879. positions[p + 1] = points[i].y + curshft * curvect.y;
  56880. positions[p + 2] = points[i].z + curshft * curvect.z;
  56881. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56882. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56883. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56884. p += 6;
  56885. j++;
  56886. }
  56887. }
  56888. while (p < positions.length) {
  56889. positions[p] = points[i].x;
  56890. positions[p + 1] = points[i].y;
  56891. positions[p + 2] = points[i].z;
  56892. p += 3;
  56893. }
  56894. };
  56895. instance.updateMeshPositions(positionFunction, false);
  56896. return instance;
  56897. }
  56898. // dashed lines creation
  56899. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56900. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56901. vertexData.applyToMesh(dashedLines, options.updatable);
  56902. dashedLines.dashSize = dashSize;
  56903. dashedLines.gapSize = gapSize;
  56904. return dashedLines;
  56905. };
  56906. /**
  56907. * Creates an extruded shape mesh.
  56908. * 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.
  56909. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56910. *
  56911. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56912. * 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
  56913. * extruded along the Z axis.
  56914. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56915. * 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.
  56916. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56917. * 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
  56918. * 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
  56919. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56921. * 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).
  56922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56923. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56924. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56925. */
  56926. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56927. if (scene === void 0) { scene = null; }
  56928. var path = options.path;
  56929. var shape = options.shape;
  56930. var scale = options.scale || 1;
  56931. var rotation = options.rotation || 0;
  56932. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56933. var updatable = options.updatable;
  56934. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56935. var instance = options.instance || null;
  56936. var invertUV = options.invertUV || false;
  56937. 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);
  56938. };
  56939. /**
  56940. * Creates an custom extruded shape mesh.
  56941. * 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.
  56942. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56943. *
  56944. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56945. * 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
  56946. * extruded along the Z axis.
  56947. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56948. * 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
  56949. * and the distance of this point from the begining of the path :
  56950. * ```javascript
  56951. * var rotationFunction = function(i, distance) {
  56952. * // do things
  56953. * return rotationValue; }
  56954. * ```
  56955. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56956. * 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
  56957. * and the distance of this point from the begining of the path :
  56958. * ```javascript
  56959. * var scaleFunction = function(i, distance) {
  56960. * // do things
  56961. * return scaleValue;}
  56962. * ```
  56963. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56964. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56965. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56966. * 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
  56967. * 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
  56968. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56969. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56970. * 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).
  56971. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56972. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56973. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56974. */
  56975. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56976. var path = options.path;
  56977. var shape = options.shape;
  56978. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56979. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56980. var ribbonCloseArray = options.ribbonCloseArray || false;
  56981. var ribbonClosePath = options.ribbonClosePath || false;
  56982. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56983. var updatable = options.updatable;
  56984. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56985. var instance = options.instance;
  56986. var invertUV = options.invertUV || false;
  56987. 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);
  56988. };
  56989. /**
  56990. * Creates lathe mesh.
  56991. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56993. *
  56994. * 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
  56995. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56996. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56997. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56998. * 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.
  56999. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  57000. * 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
  57001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57002. * 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).
  57003. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57004. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57005. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57006. */
  57007. MeshBuilder.CreateLathe = function (name, options, scene) {
  57008. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  57009. var closed = (options.closed === undefined) ? true : options.closed;
  57010. var shape = options.shape;
  57011. var radius = options.radius || 1;
  57012. var tessellation = options.tessellation || 64;
  57013. var updatable = options.updatable;
  57014. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57015. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57016. var pi2 = Math.PI * 2;
  57017. var paths = new Array();
  57018. var invertUV = options.invertUV || false;
  57019. var i = 0;
  57020. var p = 0;
  57021. var step = pi2 / tessellation * arc;
  57022. var rotated;
  57023. var path = new Array();
  57024. ;
  57025. for (i = 0; i <= tessellation; i++) {
  57026. var path = [];
  57027. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  57028. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  57029. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  57030. }
  57031. for (p = 0; p < shape.length; p++) {
  57032. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  57033. path.push(rotated);
  57034. }
  57035. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  57036. 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));
  57037. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  57038. }
  57039. paths.push(path);
  57040. }
  57041. // lathe ribbon
  57042. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57043. return lathe;
  57044. };
  57045. /**
  57046. * Creates a plane mesh.
  57047. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57048. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  57049. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  57050. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  57051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57052. * 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).
  57053. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57054. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57055. */
  57056. MeshBuilder.CreatePlane = function (name, options, scene) {
  57057. var plane = new BABYLON.Mesh(name, scene);
  57058. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57059. plane._originalBuilderSideOrientation = options.sideOrientation;
  57060. var vertexData = BABYLON.VertexData.CreatePlane(options);
  57061. vertexData.applyToMesh(plane, options.updatable);
  57062. if (options.sourcePlane) {
  57063. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  57064. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  57065. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  57066. plane.rotate(vectorProduct, product);
  57067. }
  57068. return plane;
  57069. };
  57070. /**
  57071. * Creates a ground mesh.
  57072. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  57073. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  57074. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  57075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57076. */
  57077. MeshBuilder.CreateGround = function (name, options, scene) {
  57078. var ground = new BABYLON.GroundMesh(name, scene);
  57079. ground._setReady(false);
  57080. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  57081. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  57082. ground._width = options.width || 1;
  57083. ground._height = options.height || 1;
  57084. ground._maxX = ground._width / 2;
  57085. ground._maxZ = ground._height / 2;
  57086. ground._minX = -ground._maxX;
  57087. ground._minZ = -ground._maxZ;
  57088. var vertexData = BABYLON.VertexData.CreateGround(options);
  57089. vertexData.applyToMesh(ground, options.updatable);
  57090. ground._setReady(true);
  57091. return ground;
  57092. };
  57093. /**
  57094. * Creates a tiled ground mesh.
  57095. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  57096. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  57097. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  57098. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  57099. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  57100. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  57101. * numbers of subdivisions on the ground width and height of each tile.
  57102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57103. */
  57104. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  57105. var tiledGround = new BABYLON.Mesh(name, scene);
  57106. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  57107. vertexData.applyToMesh(tiledGround, options.updatable);
  57108. return tiledGround;
  57109. };
  57110. /**
  57111. * Creates a ground mesh from a height map.
  57112. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  57113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  57114. * The parameter `url` sets the URL of the height map image resource.
  57115. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  57116. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  57117. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  57118. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  57119. * 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.
  57120. * 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).
  57121. * This function is passed the newly built mesh :
  57122. * ```javascript
  57123. * function(mesh) { // do things
  57124. * return; }
  57125. * ```
  57126. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57127. */
  57128. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  57129. var width = options.width || 10.0;
  57130. var height = options.height || 10.0;
  57131. var subdivisions = options.subdivisions || 1 | 0;
  57132. var minHeight = options.minHeight || 0.0;
  57133. var maxHeight = options.maxHeight || 1.0;
  57134. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  57135. var updatable = options.updatable;
  57136. var onReady = options.onReady;
  57137. var ground = new BABYLON.GroundMesh(name, scene);
  57138. ground._subdivisionsX = subdivisions;
  57139. ground._subdivisionsY = subdivisions;
  57140. ground._width = width;
  57141. ground._height = height;
  57142. ground._maxX = ground._width / 2.0;
  57143. ground._maxZ = ground._height / 2.0;
  57144. ground._minX = -ground._maxX;
  57145. ground._minZ = -ground._maxZ;
  57146. ground._setReady(false);
  57147. var onload = function (img) {
  57148. // Getting height map data
  57149. var canvas = document.createElement("canvas");
  57150. var context = canvas.getContext("2d");
  57151. if (!context) {
  57152. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  57153. }
  57154. if (scene.isDisposed) {
  57155. return;
  57156. }
  57157. var bufferWidth = img.width;
  57158. var bufferHeight = img.height;
  57159. canvas.width = bufferWidth;
  57160. canvas.height = bufferHeight;
  57161. context.drawImage(img, 0, 0);
  57162. // Create VertexData from map data
  57163. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  57164. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  57165. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  57166. width: width, height: height,
  57167. subdivisions: subdivisions,
  57168. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  57169. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  57170. });
  57171. vertexData.applyToMesh(ground, updatable);
  57172. //execute ready callback, if set
  57173. if (onReady) {
  57174. onReady(ground);
  57175. }
  57176. ground._setReady(true);
  57177. };
  57178. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  57179. return ground;
  57180. };
  57181. /**
  57182. * Creates a polygon mesh.
  57183. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  57184. * 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.
  57185. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57187. * 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).
  57188. * Remember you can only change the shape positions, not their number when updating a polygon.
  57189. */
  57190. MeshBuilder.CreatePolygon = function (name, options, scene) {
  57191. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57192. var shape = options.shape;
  57193. var holes = options.holes || [];
  57194. var depth = options.depth || 0;
  57195. var contours = [];
  57196. var hole = [];
  57197. for (var i = 0; i < shape.length; i++) {
  57198. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  57199. }
  57200. var epsilon = 0.00000001;
  57201. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  57202. contours.pop();
  57203. }
  57204. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  57205. for (var hNb = 0; hNb < holes.length; hNb++) {
  57206. hole = [];
  57207. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  57208. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  57209. }
  57210. polygonTriangulation.addHole(hole);
  57211. }
  57212. var polygon = polygonTriangulation.build(options.updatable, depth);
  57213. polygon._originalBuilderSideOrientation = options.sideOrientation;
  57214. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  57215. vertexData.applyToMesh(polygon, options.updatable);
  57216. return polygon;
  57217. };
  57218. ;
  57219. /**
  57220. * Creates an extruded polygon mesh, with depth in the Y direction.
  57221. * 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).
  57222. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  57223. */
  57224. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57225. return MeshBuilder.CreatePolygon(name, options, scene);
  57226. };
  57227. ;
  57228. /**
  57229. * Creates a tube mesh.
  57230. * 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.
  57231. *
  57232. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57233. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57234. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57235. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57236. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57237. * 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.
  57238. * It must return a radius value (positive float) :
  57239. * ```javascript
  57240. * var radiusFunction = function(i, distance) {
  57241. * // do things
  57242. * return radius; }
  57243. * ```
  57244. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57245. * 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
  57246. * 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
  57247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57248. * 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).
  57249. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57250. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57251. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57252. */
  57253. MeshBuilder.CreateTube = function (name, options, scene) {
  57254. var path = options.path;
  57255. var instance = options.instance;
  57256. var radius = 1.0;
  57257. if (instance) {
  57258. radius = instance.radius;
  57259. }
  57260. if (options.radius !== undefined) {
  57261. radius = options.radius;
  57262. }
  57263. ;
  57264. var tessellation = options.tessellation || 64 | 0;
  57265. var radiusFunction = options.radiusFunction || null;
  57266. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57267. var invertUV = options.invertUV || false;
  57268. var updatable = options.updatable;
  57269. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57270. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57271. // tube geometry
  57272. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57273. var tangents = path3D.getTangents();
  57274. var normals = path3D.getNormals();
  57275. var distances = path3D.getDistances();
  57276. var pi2 = Math.PI * 2;
  57277. var step = pi2 / tessellation * arc;
  57278. var returnRadius = function () { return radius; };
  57279. var radiusFunctionFinal = radiusFunction || returnRadius;
  57280. var circlePath;
  57281. var rad;
  57282. var normal;
  57283. var rotated;
  57284. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57285. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57286. for (var i = 0; i < path.length; i++) {
  57287. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57288. circlePath = Array(); // current circle array
  57289. normal = normals[i]; // current normal
  57290. for (var t = 0; t < tessellation; t++) {
  57291. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57292. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57293. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57294. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57295. circlePath[t] = rotated;
  57296. }
  57297. circlePaths[index] = circlePath;
  57298. index++;
  57299. }
  57300. // cap
  57301. var capPath = function (nbPoints, pathIndex) {
  57302. var pointCap = Array();
  57303. for (var i = 0; i < nbPoints; i++) {
  57304. pointCap.push(path[pathIndex]);
  57305. }
  57306. return pointCap;
  57307. };
  57308. switch (cap) {
  57309. case BABYLON.Mesh.NO_CAP:
  57310. break;
  57311. case BABYLON.Mesh.CAP_START:
  57312. circlePaths[0] = capPath(tessellation, 0);
  57313. circlePaths[1] = circlePaths[2].slice(0);
  57314. break;
  57315. case BABYLON.Mesh.CAP_END:
  57316. circlePaths[index] = circlePaths[index - 1].slice(0);
  57317. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57318. break;
  57319. case BABYLON.Mesh.CAP_ALL:
  57320. circlePaths[0] = capPath(tessellation, 0);
  57321. circlePaths[1] = circlePaths[2].slice(0);
  57322. circlePaths[index] = circlePaths[index - 1].slice(0);
  57323. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57324. break;
  57325. default:
  57326. break;
  57327. }
  57328. return circlePaths;
  57329. };
  57330. var path3D;
  57331. var pathArray;
  57332. if (instance) {
  57333. var arc = options.arc || instance.arc;
  57334. path3D = (instance.path3D).update(path);
  57335. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57336. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57337. instance.path3D = path3D;
  57338. instance.pathArray = pathArray;
  57339. instance.arc = arc;
  57340. instance.radius = radius;
  57341. return instance;
  57342. }
  57343. // tube creation
  57344. path3D = new BABYLON.Path3D(path);
  57345. var newPathArray = new Array();
  57346. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57347. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57348. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57349. tube.pathArray = pathArray;
  57350. tube.path3D = path3D;
  57351. tube.tessellation = tessellation;
  57352. tube.cap = cap;
  57353. tube.arc = options.arc;
  57354. tube.radius = radius;
  57355. return tube;
  57356. };
  57357. /**
  57358. * Creates a polyhedron mesh.
  57359. *
  57360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57361. * 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
  57362. * to choose the wanted type.
  57363. * The parameter `size` (positive float, default 1) sets the polygon size.
  57364. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57365. * 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`.
  57366. * 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
  57367. * 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)`).
  57368. * 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
  57369. * 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.
  57370. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57371. * 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).
  57372. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57374. */
  57375. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57376. var polyhedron = new BABYLON.Mesh(name, scene);
  57377. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57378. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57379. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57380. vertexData.applyToMesh(polyhedron, options.updatable);
  57381. return polyhedron;
  57382. };
  57383. /**
  57384. * Creates a decal mesh.
  57385. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57386. * 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.
  57387. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57388. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57389. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57390. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57391. */
  57392. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57393. var indices = sourceMesh.getIndices();
  57394. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57395. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57396. var position = options.position || BABYLON.Vector3.Zero();
  57397. var normal = options.normal || BABYLON.Vector3.Up();
  57398. var size = options.size || BABYLON.Vector3.One();
  57399. var angle = options.angle || 0;
  57400. // Getting correct rotation
  57401. if (!normal) {
  57402. var target = new BABYLON.Vector3(0, 0, 1);
  57403. var camera = sourceMesh.getScene().activeCamera;
  57404. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57405. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57406. }
  57407. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57408. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57409. var pitch = Math.atan2(normal.y, len);
  57410. // Matrix
  57411. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57412. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57413. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57414. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57415. var vertexData = new BABYLON.VertexData();
  57416. vertexData.indices = [];
  57417. vertexData.positions = [];
  57418. vertexData.normals = [];
  57419. vertexData.uvs = [];
  57420. var currentVertexDataIndex = 0;
  57421. var extractDecalVector3 = function (indexId) {
  57422. var result = new BABYLON.PositionNormalVertex();
  57423. if (!indices || !positions || !normals) {
  57424. return result;
  57425. }
  57426. var vertexId = indices[indexId];
  57427. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57428. // Send vector to decal local world
  57429. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57430. // Get normal
  57431. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57432. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57433. return result;
  57434. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57435. var clip = function (vertices, axis) {
  57436. if (vertices.length === 0) {
  57437. return vertices;
  57438. }
  57439. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57440. var clipVertices = function (v0, v1) {
  57441. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57442. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57443. };
  57444. var result = new Array();
  57445. for (var index = 0; index < vertices.length; index += 3) {
  57446. var v1Out;
  57447. var v2Out;
  57448. var v3Out;
  57449. var total = 0;
  57450. var nV1 = null;
  57451. var nV2 = null;
  57452. var nV3 = null;
  57453. var nV4 = null;
  57454. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57455. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57456. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57457. v1Out = d1 > 0;
  57458. v2Out = d2 > 0;
  57459. v3Out = d3 > 0;
  57460. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57461. switch (total) {
  57462. case 0:
  57463. result.push(vertices[index]);
  57464. result.push(vertices[index + 1]);
  57465. result.push(vertices[index + 2]);
  57466. break;
  57467. case 1:
  57468. if (v1Out) {
  57469. nV1 = vertices[index + 1];
  57470. nV2 = vertices[index + 2];
  57471. nV3 = clipVertices(vertices[index], nV1);
  57472. nV4 = clipVertices(vertices[index], nV2);
  57473. }
  57474. if (v2Out) {
  57475. nV1 = vertices[index];
  57476. nV2 = vertices[index + 2];
  57477. nV3 = clipVertices(vertices[index + 1], nV1);
  57478. nV4 = clipVertices(vertices[index + 1], nV2);
  57479. result.push(nV3);
  57480. result.push(nV2.clone());
  57481. result.push(nV1.clone());
  57482. result.push(nV2.clone());
  57483. result.push(nV3.clone());
  57484. result.push(nV4);
  57485. break;
  57486. }
  57487. if (v3Out) {
  57488. nV1 = vertices[index];
  57489. nV2 = vertices[index + 1];
  57490. nV3 = clipVertices(vertices[index + 2], nV1);
  57491. nV4 = clipVertices(vertices[index + 2], nV2);
  57492. }
  57493. if (nV1 && nV2 && nV3 && nV4) {
  57494. result.push(nV1.clone());
  57495. result.push(nV2.clone());
  57496. result.push(nV3);
  57497. result.push(nV4);
  57498. result.push(nV3.clone());
  57499. result.push(nV2.clone());
  57500. }
  57501. break;
  57502. case 2:
  57503. if (!v1Out) {
  57504. nV1 = vertices[index].clone();
  57505. nV2 = clipVertices(nV1, vertices[index + 1]);
  57506. nV3 = clipVertices(nV1, vertices[index + 2]);
  57507. result.push(nV1);
  57508. result.push(nV2);
  57509. result.push(nV3);
  57510. }
  57511. if (!v2Out) {
  57512. nV1 = vertices[index + 1].clone();
  57513. nV2 = clipVertices(nV1, vertices[index + 2]);
  57514. nV3 = clipVertices(nV1, vertices[index]);
  57515. result.push(nV1);
  57516. result.push(nV2);
  57517. result.push(nV3);
  57518. }
  57519. if (!v3Out) {
  57520. nV1 = vertices[index + 2].clone();
  57521. nV2 = clipVertices(nV1, vertices[index]);
  57522. nV3 = clipVertices(nV1, vertices[index + 1]);
  57523. result.push(nV1);
  57524. result.push(nV2);
  57525. result.push(nV3);
  57526. }
  57527. break;
  57528. case 3:
  57529. break;
  57530. }
  57531. }
  57532. return result;
  57533. };
  57534. for (var index = 0; index < indices.length; index += 3) {
  57535. var faceVertices = new Array();
  57536. faceVertices.push(extractDecalVector3(index));
  57537. faceVertices.push(extractDecalVector3(index + 1));
  57538. faceVertices.push(extractDecalVector3(index + 2));
  57539. // Clip
  57540. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57541. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57542. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57543. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57544. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57545. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57546. if (faceVertices.length === 0) {
  57547. continue;
  57548. }
  57549. // Add UVs and get back to world
  57550. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57551. var vertex = faceVertices[vIndex];
  57552. //TODO check for Int32Array | Uint32Array | Uint16Array
  57553. vertexData.indices.push(currentVertexDataIndex);
  57554. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57555. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57556. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57557. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57558. currentVertexDataIndex++;
  57559. }
  57560. }
  57561. // Return mesh
  57562. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57563. vertexData.applyToMesh(decal);
  57564. decal.position = position.clone();
  57565. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57566. return decal;
  57567. };
  57568. // Privates
  57569. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57570. // extrusion geometry
  57571. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57572. var tangents = path3D.getTangents();
  57573. var normals = path3D.getNormals();
  57574. var binormals = path3D.getBinormals();
  57575. var distances = path3D.getDistances();
  57576. var angle = 0;
  57577. var returnScale = function () { return scale !== null ? scale : 1; };
  57578. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57579. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57580. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57581. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57582. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57583. for (var i = 0; i < curve.length; i++) {
  57584. var shapePath = new Array();
  57585. var angleStep = rotate(i, distances[i]);
  57586. var scaleRatio = scl(i, distances[i]);
  57587. for (var p = 0; p < shape.length; p++) {
  57588. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57589. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57590. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57591. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57592. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57593. shapePath[p] = rotated;
  57594. }
  57595. shapePaths[index] = shapePath;
  57596. angle += angleStep;
  57597. index++;
  57598. }
  57599. // cap
  57600. var capPath = function (shapePath) {
  57601. var pointCap = Array();
  57602. var barycenter = BABYLON.Vector3.Zero();
  57603. var i;
  57604. for (i = 0; i < shapePath.length; i++) {
  57605. barycenter.addInPlace(shapePath[i]);
  57606. }
  57607. barycenter.scaleInPlace(1.0 / shapePath.length);
  57608. for (i = 0; i < shapePath.length; i++) {
  57609. pointCap.push(barycenter);
  57610. }
  57611. return pointCap;
  57612. };
  57613. switch (cap) {
  57614. case BABYLON.Mesh.NO_CAP:
  57615. break;
  57616. case BABYLON.Mesh.CAP_START:
  57617. shapePaths[0] = capPath(shapePaths[2]);
  57618. shapePaths[1] = shapePaths[2];
  57619. break;
  57620. case BABYLON.Mesh.CAP_END:
  57621. shapePaths[index] = shapePaths[index - 1];
  57622. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57623. break;
  57624. case BABYLON.Mesh.CAP_ALL:
  57625. shapePaths[0] = capPath(shapePaths[2]);
  57626. shapePaths[1] = shapePaths[2];
  57627. shapePaths[index] = shapePaths[index - 1];
  57628. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57629. break;
  57630. default:
  57631. break;
  57632. }
  57633. return shapePaths;
  57634. };
  57635. var path3D;
  57636. var pathArray;
  57637. if (instance) {
  57638. path3D = (instance.path3D).update(curve);
  57639. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57640. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57641. return instance;
  57642. }
  57643. // extruded shape creation
  57644. path3D = new BABYLON.Path3D(curve);
  57645. var newShapePaths = new Array();
  57646. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57647. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57648. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57649. extrudedGeneric.pathArray = pathArray;
  57650. extrudedGeneric.path3D = path3D;
  57651. extrudedGeneric.cap = cap;
  57652. return extrudedGeneric;
  57653. };
  57654. return MeshBuilder;
  57655. }());
  57656. BABYLON.MeshBuilder = MeshBuilder;
  57657. })(BABYLON || (BABYLON = {}));
  57658. //# sourceMappingURL=babylon.meshBuilder.js.map
  57659. "use strict";
  57660. var BABYLON;
  57661. (function (BABYLON) {
  57662. /**
  57663. * Draco compression (https://google.github.io/draco/)
  57664. */
  57665. var DracoCompression = /** @class */ (function () {
  57666. /**
  57667. * Constructor
  57668. * @param numWorkers The number of workers for async operations
  57669. */
  57670. function DracoCompression(numWorkers) {
  57671. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57672. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57673. if (!workerBlobUrl || !Worker) {
  57674. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57675. return;
  57676. }
  57677. var workers = new Array(numWorkers);
  57678. for (var i = 0; i < workers.length; i++) {
  57679. var worker = new Worker(workerBlobUrl);
  57680. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57681. workers[i] = worker;
  57682. }
  57683. this._workerPool = new BABYLON.WorkerPool(workers);
  57684. }
  57685. /**
  57686. * Stop all async operations and release resources.
  57687. */
  57688. DracoCompression.prototype.dispose = function () {
  57689. this._workerPool.dispose();
  57690. delete this._workerPool;
  57691. };
  57692. /**
  57693. * Decode Draco compressed mesh data to vertex data.
  57694. * @param data The array buffer view for the Draco compression data
  57695. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57696. * @returns A promise that resolves with the decoded vertex data
  57697. */
  57698. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57699. var _this = this;
  57700. return new Promise(function (resolve, reject) {
  57701. _this._workerPool.push(function (worker, onComplete) {
  57702. var vertexData = new BABYLON.VertexData();
  57703. var onError = function (error) {
  57704. worker.removeEventListener("error", onError);
  57705. worker.removeEventListener("message", onMessage);
  57706. reject(error);
  57707. onComplete();
  57708. };
  57709. var onMessage = function (message) {
  57710. if (message.data === "done") {
  57711. worker.removeEventListener("error", onError);
  57712. worker.removeEventListener("message", onMessage);
  57713. resolve(vertexData);
  57714. onComplete();
  57715. }
  57716. else if (message.data.id === "indices") {
  57717. vertexData.indices = message.data.value;
  57718. }
  57719. else {
  57720. vertexData.set(message.data.value, message.data.id);
  57721. }
  57722. };
  57723. worker.addEventListener("error", onError);
  57724. worker.addEventListener("message", onMessage);
  57725. var dataCopy = new Uint8Array(data.byteLength);
  57726. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57727. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57728. });
  57729. });
  57730. };
  57731. /**
  57732. * The worker function that gets converted to a blob url to pass into a worker.
  57733. */
  57734. DracoCompression._Worker = function () {
  57735. // self is actually a DedicatedWorkerGlobalScope
  57736. var _self = self;
  57737. var decodeMesh = function (data, attributes) {
  57738. var dracoModule = new DracoDecoderModule();
  57739. var buffer = new dracoModule.DecoderBuffer();
  57740. buffer.Init(data, data.byteLength);
  57741. var decoder = new dracoModule.Decoder();
  57742. var geometry;
  57743. var status;
  57744. try {
  57745. var type = decoder.GetEncodedGeometryType(buffer);
  57746. switch (type) {
  57747. case dracoModule.TRIANGULAR_MESH:
  57748. geometry = new dracoModule.Mesh();
  57749. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57750. break;
  57751. case dracoModule.POINT_CLOUD:
  57752. geometry = new dracoModule.PointCloud();
  57753. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57754. break;
  57755. default:
  57756. throw new Error("Invalid geometry type " + type);
  57757. }
  57758. if (!status.ok() || !geometry.ptr) {
  57759. throw new Error(status.error_msg());
  57760. }
  57761. var numPoints = geometry.num_points();
  57762. if (type === dracoModule.TRIANGULAR_MESH) {
  57763. var numFaces = geometry.num_faces();
  57764. var faceIndices = new dracoModule.DracoInt32Array();
  57765. try {
  57766. var indices = new Uint32Array(numFaces * 3);
  57767. for (var i = 0; i < numFaces; i++) {
  57768. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57769. var offset = i * 3;
  57770. indices[offset + 0] = faceIndices.GetValue(0);
  57771. indices[offset + 1] = faceIndices.GetValue(1);
  57772. indices[offset + 2] = faceIndices.GetValue(2);
  57773. }
  57774. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57775. }
  57776. finally {
  57777. dracoModule.destroy(faceIndices);
  57778. }
  57779. }
  57780. for (var kind in attributes) {
  57781. var uniqueId = attributes[kind];
  57782. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57783. var dracoData = new dracoModule.DracoFloat32Array();
  57784. try {
  57785. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57786. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57787. for (var i = 0; i < babylonData.length; i++) {
  57788. babylonData[i] = dracoData.GetValue(i);
  57789. }
  57790. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57791. }
  57792. finally {
  57793. dracoModule.destroy(dracoData);
  57794. }
  57795. }
  57796. }
  57797. finally {
  57798. if (geometry) {
  57799. dracoModule.destroy(geometry);
  57800. }
  57801. dracoModule.destroy(decoder);
  57802. dracoModule.destroy(buffer);
  57803. }
  57804. _self.postMessage("done");
  57805. };
  57806. _self.onmessage = function (event) {
  57807. switch (event.data.id) {
  57808. case "initDecoder": {
  57809. importScripts(event.data.url);
  57810. break;
  57811. }
  57812. case "decodeMesh": {
  57813. decodeMesh(event.data.data, event.data.attributes);
  57814. break;
  57815. }
  57816. }
  57817. };
  57818. };
  57819. DracoCompression._GetDefaultDecoderUrl = function () {
  57820. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57821. return null;
  57822. }
  57823. for (var i = 0; i < document.scripts.length; i++) {
  57824. if (document.scripts[i].type === "text/x-draco-decoder") {
  57825. return document.scripts[i].src;
  57826. }
  57827. }
  57828. return null;
  57829. };
  57830. /**
  57831. * Gets the url to the draco decoder if available.
  57832. */
  57833. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57834. return DracoCompression;
  57835. }());
  57836. BABYLON.DracoCompression = DracoCompression;
  57837. })(BABYLON || (BABYLON = {}));
  57838. //# sourceMappingURL=babylon.dracoCompression.js.map
  57839. "use strict";
  57840. var BABYLON;
  57841. (function (BABYLON) {
  57842. var AudioEngine = /** @class */ (function () {
  57843. function AudioEngine() {
  57844. this._audioContext = null;
  57845. this._audioContextInitialized = false;
  57846. this.canUseWebAudio = false;
  57847. this.WarnedWebAudioUnsupported = false;
  57848. this.unlocked = false;
  57849. this.isMP3supported = false;
  57850. this.isOGGsupported = false;
  57851. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57852. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57853. this.canUseWebAudio = true;
  57854. }
  57855. var audioElem = document.createElement('audio');
  57856. try {
  57857. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57858. this.isMP3supported = true;
  57859. }
  57860. }
  57861. catch (e) {
  57862. // protect error during capability check.
  57863. }
  57864. try {
  57865. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57866. this.isOGGsupported = true;
  57867. }
  57868. }
  57869. catch (e) {
  57870. // protect error during capability check.
  57871. }
  57872. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57873. this._unlockiOSaudio();
  57874. }
  57875. else {
  57876. this.unlocked = true;
  57877. }
  57878. }
  57879. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57880. get: function () {
  57881. if (!this._audioContextInitialized) {
  57882. this._initializeAudioContext();
  57883. }
  57884. return this._audioContext;
  57885. },
  57886. enumerable: true,
  57887. configurable: true
  57888. });
  57889. AudioEngine.prototype._unlockiOSaudio = function () {
  57890. var _this = this;
  57891. var unlockaudio = function () {
  57892. if (!_this.audioContext) {
  57893. return;
  57894. }
  57895. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57896. var source = _this.audioContext.createBufferSource();
  57897. source.buffer = buffer;
  57898. source.connect(_this.audioContext.destination);
  57899. source.start(0);
  57900. setTimeout(function () {
  57901. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57902. _this.unlocked = true;
  57903. window.removeEventListener('touchend', unlockaudio, false);
  57904. if (_this.onAudioUnlocked) {
  57905. _this.onAudioUnlocked();
  57906. }
  57907. }
  57908. }, 0);
  57909. };
  57910. window.addEventListener('touchend', unlockaudio, false);
  57911. };
  57912. AudioEngine.prototype._initializeAudioContext = function () {
  57913. try {
  57914. if (this.canUseWebAudio) {
  57915. this._audioContext = new AudioContext();
  57916. // create a global volume gain node
  57917. this.masterGain = this._audioContext.createGain();
  57918. this.masterGain.gain.value = 1;
  57919. this.masterGain.connect(this._audioContext.destination);
  57920. this._audioContextInitialized = true;
  57921. }
  57922. }
  57923. catch (e) {
  57924. this.canUseWebAudio = false;
  57925. BABYLON.Tools.Error("Web Audio: " + e.message);
  57926. }
  57927. };
  57928. AudioEngine.prototype.dispose = function () {
  57929. if (this.canUseWebAudio && this._audioContextInitialized) {
  57930. if (this._connectedAnalyser && this._audioContext) {
  57931. this._connectedAnalyser.stopDebugCanvas();
  57932. this._connectedAnalyser.dispose();
  57933. this.masterGain.disconnect();
  57934. this.masterGain.connect(this._audioContext.destination);
  57935. this._connectedAnalyser = null;
  57936. }
  57937. this.masterGain.gain.value = 1;
  57938. }
  57939. this.WarnedWebAudioUnsupported = false;
  57940. };
  57941. AudioEngine.prototype.getGlobalVolume = function () {
  57942. if (this.canUseWebAudio && this._audioContextInitialized) {
  57943. return this.masterGain.gain.value;
  57944. }
  57945. else {
  57946. return -1;
  57947. }
  57948. };
  57949. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57950. if (this.canUseWebAudio && this._audioContextInitialized) {
  57951. this.masterGain.gain.value = newVolume;
  57952. }
  57953. };
  57954. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57955. if (this._connectedAnalyser) {
  57956. this._connectedAnalyser.stopDebugCanvas();
  57957. }
  57958. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57959. this._connectedAnalyser = analyser;
  57960. this.masterGain.disconnect();
  57961. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57962. }
  57963. };
  57964. return AudioEngine;
  57965. }());
  57966. BABYLON.AudioEngine = AudioEngine;
  57967. })(BABYLON || (BABYLON = {}));
  57968. //# sourceMappingURL=babylon.audioEngine.js.map
  57969. "use strict";
  57970. var BABYLON;
  57971. (function (BABYLON) {
  57972. var Sound = /** @class */ (function () {
  57973. /**
  57974. * Create a sound and attach it to a scene
  57975. * @param name Name of your sound
  57976. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57977. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57978. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57979. */
  57980. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57981. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57982. var _this = this;
  57983. this.autoplay = false;
  57984. this.loop = false;
  57985. this.useCustomAttenuation = false;
  57986. this.spatialSound = false;
  57987. this.refDistance = 1;
  57988. this.rolloffFactor = 1;
  57989. this.maxDistance = 100;
  57990. this.distanceModel = "linear";
  57991. this._panningModel = "equalpower";
  57992. this._playbackRate = 1;
  57993. this._streaming = false;
  57994. this._startTime = 0;
  57995. this._startOffset = 0;
  57996. this._position = BABYLON.Vector3.Zero();
  57997. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57998. this._volume = 1;
  57999. this._isReadyToPlay = false;
  58000. this.isPlaying = false;
  58001. this.isPaused = false;
  58002. this._isDirectional = false;
  58003. // Used if you'd like to create a directional sound.
  58004. // If not set, the sound will be omnidirectional
  58005. this._coneInnerAngle = 360;
  58006. this._coneOuterAngle = 360;
  58007. this._coneOuterGain = 0;
  58008. this._isOutputConnected = false;
  58009. this._urlType = "Unknown";
  58010. this.name = name;
  58011. this._scene = scene;
  58012. this._readyToPlayCallback = readyToPlayCallback;
  58013. // Default custom attenuation function is a linear attenuation
  58014. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  58015. if (currentDistance < maxDistance) {
  58016. return currentVolume * (1 - currentDistance / maxDistance);
  58017. }
  58018. else {
  58019. return 0;
  58020. }
  58021. };
  58022. if (options) {
  58023. this.autoplay = options.autoplay || false;
  58024. this.loop = options.loop || false;
  58025. // if volume === 0, we need another way to check this option
  58026. if (options.volume !== undefined) {
  58027. this._volume = options.volume;
  58028. }
  58029. this.spatialSound = options.spatialSound || false;
  58030. this.maxDistance = options.maxDistance || 100;
  58031. this.useCustomAttenuation = options.useCustomAttenuation || false;
  58032. this.rolloffFactor = options.rolloffFactor || 1;
  58033. this.refDistance = options.refDistance || 1;
  58034. this.distanceModel = options.distanceModel || "linear";
  58035. this._playbackRate = options.playbackRate || 1;
  58036. this._streaming = options.streaming || false;
  58037. }
  58038. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58039. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  58040. this._soundGain.gain.value = this._volume;
  58041. this._inputAudioNode = this._soundGain;
  58042. this._ouputAudioNode = this._soundGain;
  58043. if (this.spatialSound) {
  58044. this._createSpatialParameters();
  58045. }
  58046. this._scene.mainSoundTrack.AddSound(this);
  58047. var validParameter = true;
  58048. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  58049. if (urlOrArrayBuffer) {
  58050. try {
  58051. if (typeof (urlOrArrayBuffer) === "string")
  58052. this._urlType = "String";
  58053. if (Array.isArray(urlOrArrayBuffer))
  58054. this._urlType = "Array";
  58055. if (urlOrArrayBuffer instanceof ArrayBuffer)
  58056. this._urlType = "ArrayBuffer";
  58057. var urls = [];
  58058. var codecSupportedFound = false;
  58059. switch (this._urlType) {
  58060. case "ArrayBuffer":
  58061. if (urlOrArrayBuffer.byteLength > 0) {
  58062. codecSupportedFound = true;
  58063. this._soundLoaded(urlOrArrayBuffer);
  58064. }
  58065. break;
  58066. case "String":
  58067. urls.push(urlOrArrayBuffer);
  58068. case "Array":
  58069. if (urls.length === 0)
  58070. urls = urlOrArrayBuffer;
  58071. // If we found a supported format, we load it immediately and stop the loop
  58072. for (var i = 0; i < urls.length; i++) {
  58073. var url = urls[i];
  58074. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  58075. codecSupportedFound = true;
  58076. }
  58077. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  58078. codecSupportedFound = true;
  58079. }
  58080. if (url.indexOf(".wav", url.length - 4) !== -1) {
  58081. codecSupportedFound = true;
  58082. }
  58083. if (url.indexOf("blob:") !== -1) {
  58084. codecSupportedFound = true;
  58085. }
  58086. if (codecSupportedFound) {
  58087. // Loading sound using XHR2
  58088. if (!this._streaming) {
  58089. this._scene._loadFile(url, function (data) {
  58090. _this._soundLoaded(data);
  58091. }, undefined, true, true, function (exception) {
  58092. if (exception) {
  58093. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  58094. }
  58095. BABYLON.Tools.Error("Sound creation aborted.");
  58096. _this._scene.mainSoundTrack.RemoveSound(_this);
  58097. });
  58098. }
  58099. else {
  58100. this._htmlAudioElement = new Audio(url);
  58101. this._htmlAudioElement.controls = false;
  58102. this._htmlAudioElement.loop = this.loop;
  58103. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  58104. this._htmlAudioElement.preload = "auto";
  58105. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  58106. _this._isReadyToPlay = true;
  58107. if (_this.autoplay) {
  58108. _this.play();
  58109. }
  58110. if (_this._readyToPlayCallback) {
  58111. _this._readyToPlayCallback();
  58112. }
  58113. });
  58114. document.body.appendChild(this._htmlAudioElement);
  58115. }
  58116. break;
  58117. }
  58118. }
  58119. break;
  58120. default:
  58121. validParameter = false;
  58122. break;
  58123. }
  58124. if (!validParameter) {
  58125. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  58126. }
  58127. else {
  58128. if (!codecSupportedFound) {
  58129. this._isReadyToPlay = true;
  58130. // Simulating a ready to play event to avoid breaking code path
  58131. if (this._readyToPlayCallback) {
  58132. window.setTimeout(function () {
  58133. if (_this._readyToPlayCallback) {
  58134. _this._readyToPlayCallback();
  58135. }
  58136. }, 1000);
  58137. }
  58138. }
  58139. }
  58140. }
  58141. catch (ex) {
  58142. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  58143. this._scene.mainSoundTrack.RemoveSound(this);
  58144. }
  58145. }
  58146. }
  58147. else {
  58148. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  58149. this._scene.mainSoundTrack.AddSound(this);
  58150. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  58151. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  58152. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  58153. }
  58154. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  58155. if (this._readyToPlayCallback) {
  58156. window.setTimeout(function () {
  58157. if (_this._readyToPlayCallback) {
  58158. _this._readyToPlayCallback();
  58159. }
  58160. }, 1000);
  58161. }
  58162. }
  58163. }
  58164. Sound.prototype.dispose = function () {
  58165. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58166. if (this.isPlaying) {
  58167. this.stop();
  58168. }
  58169. this._isReadyToPlay = false;
  58170. if (this.soundTrackId === -1) {
  58171. this._scene.mainSoundTrack.RemoveSound(this);
  58172. }
  58173. else {
  58174. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  58175. }
  58176. if (this._soundGain) {
  58177. this._soundGain.disconnect();
  58178. this._soundGain = null;
  58179. }
  58180. if (this._soundPanner) {
  58181. this._soundPanner.disconnect();
  58182. this._soundPanner = null;
  58183. }
  58184. if (this._soundSource) {
  58185. this._soundSource.disconnect();
  58186. this._soundSource = null;
  58187. }
  58188. this._audioBuffer = null;
  58189. if (this._htmlAudioElement) {
  58190. this._htmlAudioElement.pause();
  58191. this._htmlAudioElement.src = "";
  58192. document.body.removeChild(this._htmlAudioElement);
  58193. }
  58194. if (this._connectedMesh && this._registerFunc) {
  58195. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58196. this._connectedMesh = null;
  58197. }
  58198. }
  58199. };
  58200. Sound.prototype.isReady = function () {
  58201. return this._isReadyToPlay;
  58202. };
  58203. Sound.prototype._soundLoaded = function (audioData) {
  58204. var _this = this;
  58205. if (!BABYLON.Engine.audioEngine.audioContext) {
  58206. return;
  58207. }
  58208. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  58209. _this._audioBuffer = buffer;
  58210. _this._isReadyToPlay = true;
  58211. if (_this.autoplay) {
  58212. _this.play();
  58213. }
  58214. if (_this._readyToPlayCallback) {
  58215. _this._readyToPlayCallback();
  58216. }
  58217. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  58218. };
  58219. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  58220. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58221. this._audioBuffer = audioBuffer;
  58222. this._isReadyToPlay = true;
  58223. }
  58224. };
  58225. Sound.prototype.updateOptions = function (options) {
  58226. if (options) {
  58227. this.loop = options.loop || this.loop;
  58228. this.maxDistance = options.maxDistance || this.maxDistance;
  58229. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  58230. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  58231. this.refDistance = options.refDistance || this.refDistance;
  58232. this.distanceModel = options.distanceModel || this.distanceModel;
  58233. this._playbackRate = options.playbackRate || this._playbackRate;
  58234. this._updateSpatialParameters();
  58235. if (this.isPlaying) {
  58236. if (this._streaming) {
  58237. this._htmlAudioElement.playbackRate = this._playbackRate;
  58238. }
  58239. else {
  58240. if (this._soundSource) {
  58241. this._soundSource.playbackRate.value = this._playbackRate;
  58242. }
  58243. }
  58244. }
  58245. }
  58246. };
  58247. Sound.prototype._createSpatialParameters = function () {
  58248. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58249. if (this._scene.headphone) {
  58250. this._panningModel = "HRTF";
  58251. }
  58252. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58253. this._updateSpatialParameters();
  58254. this._soundPanner.connect(this._ouputAudioNode);
  58255. this._inputAudioNode = this._soundPanner;
  58256. }
  58257. };
  58258. Sound.prototype._updateSpatialParameters = function () {
  58259. if (this.spatialSound && this._soundPanner) {
  58260. if (this.useCustomAttenuation) {
  58261. // Tricks to disable in a way embedded Web Audio attenuation
  58262. this._soundPanner.distanceModel = "linear";
  58263. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58264. this._soundPanner.refDistance = 1;
  58265. this._soundPanner.rolloffFactor = 1;
  58266. this._soundPanner.panningModel = this._panningModel;
  58267. }
  58268. else {
  58269. this._soundPanner.distanceModel = this.distanceModel;
  58270. this._soundPanner.maxDistance = this.maxDistance;
  58271. this._soundPanner.refDistance = this.refDistance;
  58272. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58273. this._soundPanner.panningModel = this._panningModel;
  58274. }
  58275. }
  58276. };
  58277. Sound.prototype.switchPanningModelToHRTF = function () {
  58278. this._panningModel = "HRTF";
  58279. this._switchPanningModel();
  58280. };
  58281. Sound.prototype.switchPanningModelToEqualPower = function () {
  58282. this._panningModel = "equalpower";
  58283. this._switchPanningModel();
  58284. };
  58285. Sound.prototype._switchPanningModel = function () {
  58286. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58287. this._soundPanner.panningModel = this._panningModel;
  58288. }
  58289. };
  58290. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58292. if (this._isOutputConnected) {
  58293. this._ouputAudioNode.disconnect();
  58294. }
  58295. this._ouputAudioNode.connect(soundTrackAudioNode);
  58296. this._isOutputConnected = true;
  58297. }
  58298. };
  58299. /**
  58300. * Transform this sound into a directional source
  58301. * @param coneInnerAngle Size of the inner cone in degree
  58302. * @param coneOuterAngle Size of the outer cone in degree
  58303. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58304. */
  58305. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58306. if (coneOuterAngle < coneInnerAngle) {
  58307. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58308. return;
  58309. }
  58310. this._coneInnerAngle = coneInnerAngle;
  58311. this._coneOuterAngle = coneOuterAngle;
  58312. this._coneOuterGain = coneOuterGain;
  58313. this._isDirectional = true;
  58314. if (this.isPlaying && this.loop) {
  58315. this.stop();
  58316. this.play();
  58317. }
  58318. };
  58319. Sound.prototype.setPosition = function (newPosition) {
  58320. this._position = newPosition;
  58321. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58322. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58323. }
  58324. };
  58325. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58326. this._localDirection = newLocalDirection;
  58327. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58328. this._updateDirection();
  58329. }
  58330. };
  58331. Sound.prototype._updateDirection = function () {
  58332. if (!this._connectedMesh || !this._soundPanner) {
  58333. return;
  58334. }
  58335. var mat = this._connectedMesh.getWorldMatrix();
  58336. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58337. direction.normalize();
  58338. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58339. };
  58340. Sound.prototype.updateDistanceFromListener = function () {
  58341. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58342. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58343. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58344. }
  58345. };
  58346. Sound.prototype.setAttenuationFunction = function (callback) {
  58347. this._customAttenuationFunction = callback;
  58348. };
  58349. /**
  58350. * Play the sound
  58351. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58352. * @param offset (optional) Start the sound setting it at a specific time
  58353. */
  58354. Sound.prototype.play = function (time, offset) {
  58355. var _this = this;
  58356. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58357. try {
  58358. if (this._startOffset < 0) {
  58359. time = -this._startOffset;
  58360. this._startOffset = 0;
  58361. }
  58362. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58363. if (!this._soundSource || !this._streamingSource) {
  58364. if (this.spatialSound && this._soundPanner) {
  58365. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58366. if (this._isDirectional) {
  58367. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58368. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58369. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58370. if (this._connectedMesh) {
  58371. this._updateDirection();
  58372. }
  58373. else {
  58374. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58375. }
  58376. }
  58377. }
  58378. }
  58379. if (this._streaming) {
  58380. if (!this._streamingSource) {
  58381. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58382. this._htmlAudioElement.onended = function () { _this._onended(); };
  58383. this._htmlAudioElement.playbackRate = this._playbackRate;
  58384. }
  58385. this._streamingSource.disconnect();
  58386. this._streamingSource.connect(this._inputAudioNode);
  58387. this._htmlAudioElement.play();
  58388. }
  58389. else {
  58390. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58391. this._soundSource.buffer = this._audioBuffer;
  58392. this._soundSource.connect(this._inputAudioNode);
  58393. this._soundSource.loop = this.loop;
  58394. this._soundSource.playbackRate.value = this._playbackRate;
  58395. this._soundSource.onended = function () { _this._onended(); };
  58396. if (this._soundSource.buffer) {
  58397. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58398. }
  58399. }
  58400. this._startTime = startTime;
  58401. this.isPlaying = true;
  58402. this.isPaused = false;
  58403. }
  58404. catch (ex) {
  58405. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58406. }
  58407. }
  58408. };
  58409. Sound.prototype._onended = function () {
  58410. this.isPlaying = false;
  58411. if (this.onended) {
  58412. this.onended();
  58413. }
  58414. };
  58415. /**
  58416. * Stop the sound
  58417. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58418. */
  58419. Sound.prototype.stop = function (time) {
  58420. if (this.isPlaying) {
  58421. if (this._streaming) {
  58422. this._htmlAudioElement.pause();
  58423. // Test needed for Firefox or it will generate an Invalid State Error
  58424. if (this._htmlAudioElement.currentTime > 0) {
  58425. this._htmlAudioElement.currentTime = 0;
  58426. }
  58427. }
  58428. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58429. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58430. this._soundSource.stop(stopTime);
  58431. this._soundSource.onended = function () { };
  58432. if (!this.isPaused) {
  58433. this._startOffset = 0;
  58434. }
  58435. }
  58436. this.isPlaying = false;
  58437. }
  58438. };
  58439. Sound.prototype.pause = function () {
  58440. if (this.isPlaying) {
  58441. this.isPaused = true;
  58442. if (this._streaming) {
  58443. this._htmlAudioElement.pause();
  58444. }
  58445. else if (BABYLON.Engine.audioEngine.audioContext) {
  58446. this.stop(0);
  58447. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58448. }
  58449. }
  58450. };
  58451. Sound.prototype.setVolume = function (newVolume, time) {
  58452. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58453. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58454. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58455. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58456. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58457. }
  58458. else {
  58459. this._soundGain.gain.value = newVolume;
  58460. }
  58461. }
  58462. this._volume = newVolume;
  58463. };
  58464. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58465. this._playbackRate = newPlaybackRate;
  58466. if (this.isPlaying) {
  58467. if (this._streaming) {
  58468. this._htmlAudioElement.playbackRate = this._playbackRate;
  58469. }
  58470. else if (this._soundSource) {
  58471. this._soundSource.playbackRate.value = this._playbackRate;
  58472. }
  58473. }
  58474. };
  58475. Sound.prototype.getVolume = function () {
  58476. return this._volume;
  58477. };
  58478. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58479. var _this = this;
  58480. if (this._connectedMesh && this._registerFunc) {
  58481. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58482. this._registerFunc = null;
  58483. }
  58484. this._connectedMesh = meshToConnectTo;
  58485. if (!this.spatialSound) {
  58486. this.spatialSound = true;
  58487. this._createSpatialParameters();
  58488. if (this.isPlaying && this.loop) {
  58489. this.stop();
  58490. this.play();
  58491. }
  58492. }
  58493. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58494. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58495. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58496. };
  58497. Sound.prototype.detachFromMesh = function () {
  58498. if (this._connectedMesh && this._registerFunc) {
  58499. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58500. this._registerFunc = null;
  58501. this._connectedMesh = null;
  58502. }
  58503. };
  58504. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58505. if (!node.getBoundingInfo) {
  58506. return;
  58507. }
  58508. var mesh = node;
  58509. var boundingInfo = mesh.getBoundingInfo();
  58510. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58511. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58512. this._updateDirection();
  58513. }
  58514. };
  58515. Sound.prototype.clone = function () {
  58516. var _this = this;
  58517. if (!this._streaming) {
  58518. var setBufferAndRun = function () {
  58519. if (_this._isReadyToPlay) {
  58520. clonedSound._audioBuffer = _this.getAudioBuffer();
  58521. clonedSound._isReadyToPlay = true;
  58522. if (clonedSound.autoplay) {
  58523. clonedSound.play();
  58524. }
  58525. }
  58526. else {
  58527. window.setTimeout(setBufferAndRun, 300);
  58528. }
  58529. };
  58530. var currentOptions = {
  58531. autoplay: this.autoplay, loop: this.loop,
  58532. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58533. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58534. refDistance: this.refDistance, distanceModel: this.distanceModel
  58535. };
  58536. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58537. if (this.useCustomAttenuation) {
  58538. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58539. }
  58540. clonedSound.setPosition(this._position);
  58541. clonedSound.setPlaybackRate(this._playbackRate);
  58542. setBufferAndRun();
  58543. return clonedSound;
  58544. }
  58545. else {
  58546. return null;
  58547. }
  58548. };
  58549. Sound.prototype.getAudioBuffer = function () {
  58550. return this._audioBuffer;
  58551. };
  58552. Sound.prototype.serialize = function () {
  58553. var serializationObject = {
  58554. name: this.name,
  58555. url: this.name,
  58556. autoplay: this.autoplay,
  58557. loop: this.loop,
  58558. volume: this._volume,
  58559. spatialSound: this.spatialSound,
  58560. maxDistance: this.maxDistance,
  58561. rolloffFactor: this.rolloffFactor,
  58562. refDistance: this.refDistance,
  58563. distanceModel: this.distanceModel,
  58564. playbackRate: this._playbackRate,
  58565. panningModel: this._panningModel,
  58566. soundTrackId: this.soundTrackId
  58567. };
  58568. if (this.spatialSound) {
  58569. if (this._connectedMesh)
  58570. serializationObject.connectedMeshId = this._connectedMesh.id;
  58571. serializationObject.position = this._position.asArray();
  58572. serializationObject.refDistance = this.refDistance;
  58573. serializationObject.distanceModel = this.distanceModel;
  58574. serializationObject.isDirectional = this._isDirectional;
  58575. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58576. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58577. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58578. serializationObject.coneOuterGain = this._coneOuterGain;
  58579. }
  58580. return serializationObject;
  58581. };
  58582. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58583. var soundName = parsedSound.name;
  58584. var soundUrl;
  58585. if (parsedSound.url) {
  58586. soundUrl = rootUrl + parsedSound.url;
  58587. }
  58588. else {
  58589. soundUrl = rootUrl + soundName;
  58590. }
  58591. var options = {
  58592. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58593. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58594. rolloffFactor: parsedSound.rolloffFactor,
  58595. refDistance: parsedSound.refDistance,
  58596. distanceModel: parsedSound.distanceModel,
  58597. playbackRate: parsedSound.playbackRate
  58598. };
  58599. var newSound;
  58600. if (!sourceSound) {
  58601. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58602. scene._addPendingData(newSound);
  58603. }
  58604. else {
  58605. var setBufferAndRun = function () {
  58606. if (sourceSound._isReadyToPlay) {
  58607. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58608. newSound._isReadyToPlay = true;
  58609. if (newSound.autoplay) {
  58610. newSound.play();
  58611. }
  58612. }
  58613. else {
  58614. window.setTimeout(setBufferAndRun, 300);
  58615. }
  58616. };
  58617. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58618. setBufferAndRun();
  58619. }
  58620. if (parsedSound.position) {
  58621. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58622. newSound.setPosition(soundPosition);
  58623. }
  58624. if (parsedSound.isDirectional) {
  58625. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58626. if (parsedSound.localDirectionToMesh) {
  58627. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58628. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58629. }
  58630. }
  58631. if (parsedSound.connectedMeshId) {
  58632. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58633. if (connectedMesh) {
  58634. newSound.attachToMesh(connectedMesh);
  58635. }
  58636. }
  58637. return newSound;
  58638. };
  58639. return Sound;
  58640. }());
  58641. BABYLON.Sound = Sound;
  58642. })(BABYLON || (BABYLON = {}));
  58643. //# sourceMappingURL=babylon.sound.js.map
  58644. "use strict";
  58645. var BABYLON;
  58646. (function (BABYLON) {
  58647. var SoundTrack = /** @class */ (function () {
  58648. function SoundTrack(scene, options) {
  58649. this.id = -1;
  58650. this._isMainTrack = false;
  58651. this._isInitialized = false;
  58652. this._scene = scene;
  58653. this.soundCollection = new Array();
  58654. this._options = options;
  58655. if (!this._isMainTrack) {
  58656. this._scene.soundTracks.push(this);
  58657. this.id = this._scene.soundTracks.length - 1;
  58658. }
  58659. }
  58660. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58661. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58662. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58663. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58664. if (this._options) {
  58665. if (this._options.volume) {
  58666. this._outputAudioNode.gain.value = this._options.volume;
  58667. }
  58668. if (this._options.mainTrack) {
  58669. this._isMainTrack = this._options.mainTrack;
  58670. }
  58671. }
  58672. this._isInitialized = true;
  58673. }
  58674. };
  58675. SoundTrack.prototype.dispose = function () {
  58676. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58677. if (this._connectedAnalyser) {
  58678. this._connectedAnalyser.stopDebugCanvas();
  58679. }
  58680. while (this.soundCollection.length) {
  58681. this.soundCollection[0].dispose();
  58682. }
  58683. if (this._outputAudioNode) {
  58684. this._outputAudioNode.disconnect();
  58685. }
  58686. this._outputAudioNode = null;
  58687. }
  58688. };
  58689. SoundTrack.prototype.AddSound = function (sound) {
  58690. if (!this._isInitialized) {
  58691. this._initializeSoundTrackAudioGraph();
  58692. }
  58693. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58694. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58695. }
  58696. if (sound.soundTrackId) {
  58697. if (sound.soundTrackId === -1) {
  58698. this._scene.mainSoundTrack.RemoveSound(sound);
  58699. }
  58700. else {
  58701. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58702. }
  58703. }
  58704. this.soundCollection.push(sound);
  58705. sound.soundTrackId = this.id;
  58706. };
  58707. SoundTrack.prototype.RemoveSound = function (sound) {
  58708. var index = this.soundCollection.indexOf(sound);
  58709. if (index !== -1) {
  58710. this.soundCollection.splice(index, 1);
  58711. }
  58712. };
  58713. SoundTrack.prototype.setVolume = function (newVolume) {
  58714. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58715. this._outputAudioNode.gain.value = newVolume;
  58716. }
  58717. };
  58718. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58719. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58720. for (var i = 0; i < this.soundCollection.length; i++) {
  58721. this.soundCollection[i].switchPanningModelToHRTF();
  58722. }
  58723. }
  58724. };
  58725. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58726. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58727. for (var i = 0; i < this.soundCollection.length; i++) {
  58728. this.soundCollection[i].switchPanningModelToEqualPower();
  58729. }
  58730. }
  58731. };
  58732. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58733. if (this._connectedAnalyser) {
  58734. this._connectedAnalyser.stopDebugCanvas();
  58735. }
  58736. this._connectedAnalyser = analyser;
  58737. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58738. this._outputAudioNode.disconnect();
  58739. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58740. }
  58741. };
  58742. return SoundTrack;
  58743. }());
  58744. BABYLON.SoundTrack = SoundTrack;
  58745. })(BABYLON || (BABYLON = {}));
  58746. //# sourceMappingURL=babylon.soundtrack.js.map
  58747. "use strict";
  58748. var BABYLON;
  58749. (function (BABYLON) {
  58750. var Analyser = /** @class */ (function () {
  58751. function Analyser(scene) {
  58752. this.SMOOTHING = 0.75;
  58753. this.FFT_SIZE = 512;
  58754. this.BARGRAPHAMPLITUDE = 256;
  58755. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58756. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58757. this._scene = scene;
  58758. this._audioEngine = BABYLON.Engine.audioEngine;
  58759. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58760. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58761. this._webAudioAnalyser.minDecibels = -140;
  58762. this._webAudioAnalyser.maxDecibels = 0;
  58763. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58764. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58765. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58766. }
  58767. }
  58768. Analyser.prototype.getFrequencyBinCount = function () {
  58769. if (this._audioEngine.canUseWebAudio) {
  58770. return this._webAudioAnalyser.frequencyBinCount;
  58771. }
  58772. else {
  58773. return 0;
  58774. }
  58775. };
  58776. Analyser.prototype.getByteFrequencyData = function () {
  58777. if (this._audioEngine.canUseWebAudio) {
  58778. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58779. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58780. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58781. }
  58782. return this._byteFreqs;
  58783. };
  58784. Analyser.prototype.getByteTimeDomainData = function () {
  58785. if (this._audioEngine.canUseWebAudio) {
  58786. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58787. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58788. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58789. }
  58790. return this._byteTime;
  58791. };
  58792. Analyser.prototype.getFloatFrequencyData = function () {
  58793. if (this._audioEngine.canUseWebAudio) {
  58794. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58795. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58796. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58797. }
  58798. return this._floatFreqs;
  58799. };
  58800. Analyser.prototype.drawDebugCanvas = function () {
  58801. var _this = this;
  58802. if (this._audioEngine.canUseWebAudio) {
  58803. if (!this._debugCanvas) {
  58804. this._debugCanvas = document.createElement("canvas");
  58805. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58806. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58807. this._debugCanvas.style.position = "absolute";
  58808. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58809. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58810. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58811. document.body.appendChild(this._debugCanvas);
  58812. this._registerFunc = function () {
  58813. _this.drawDebugCanvas();
  58814. };
  58815. this._scene.registerBeforeRender(this._registerFunc);
  58816. }
  58817. if (this._registerFunc && this._debugCanvasContext) {
  58818. var workingArray = this.getByteFrequencyData();
  58819. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58820. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58821. // Draw the frequency domain chart.
  58822. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58823. var value = workingArray[i];
  58824. var percent = value / this.BARGRAPHAMPLITUDE;
  58825. var height = this.DEBUGCANVASSIZE.height * percent;
  58826. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58827. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58828. var hue = i / this.getFrequencyBinCount() * 360;
  58829. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58830. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58831. }
  58832. }
  58833. }
  58834. };
  58835. Analyser.prototype.stopDebugCanvas = function () {
  58836. if (this._debugCanvas) {
  58837. if (this._registerFunc) {
  58838. this._scene.unregisterBeforeRender(this._registerFunc);
  58839. this._registerFunc = null;
  58840. }
  58841. document.body.removeChild(this._debugCanvas);
  58842. this._debugCanvas = null;
  58843. this._debugCanvasContext = null;
  58844. }
  58845. };
  58846. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58847. if (this._audioEngine.canUseWebAudio) {
  58848. inputAudioNode.connect(this._webAudioAnalyser);
  58849. this._webAudioAnalyser.connect(outputAudioNode);
  58850. }
  58851. };
  58852. Analyser.prototype.dispose = function () {
  58853. if (this._audioEngine.canUseWebAudio) {
  58854. this._webAudioAnalyser.disconnect();
  58855. }
  58856. };
  58857. return Analyser;
  58858. }());
  58859. BABYLON.Analyser = Analyser;
  58860. })(BABYLON || (BABYLON = {}));
  58861. //# sourceMappingURL=babylon.analyser.js.map
  58862. "use strict";
  58863. var BABYLON;
  58864. (function (BABYLON) {
  58865. var CubeTexture = /** @class */ (function (_super) {
  58866. __extends(CubeTexture, _super);
  58867. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58868. if (extensions === void 0) { extensions = null; }
  58869. if (noMipmap === void 0) { noMipmap = false; }
  58870. if (files === void 0) { files = null; }
  58871. if (onLoad === void 0) { onLoad = null; }
  58872. if (onError === void 0) { onError = null; }
  58873. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58874. if (prefiltered === void 0) { prefiltered = false; }
  58875. if (forcedExtension === void 0) { forcedExtension = null; }
  58876. var _this = _super.call(this, scene) || this;
  58877. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58878. /**
  58879. * Gets or sets the center of the bounding box associated with the cube texture
  58880. * It must define where the camera used to render the texture was set
  58881. */
  58882. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58883. _this.name = rootUrl;
  58884. _this.url = rootUrl;
  58885. _this._noMipmap = noMipmap;
  58886. _this.hasAlpha = false;
  58887. _this._format = format;
  58888. _this._prefiltered = prefiltered;
  58889. _this.isCube = true;
  58890. _this._textureMatrix = BABYLON.Matrix.Identity();
  58891. if (prefiltered) {
  58892. _this.gammaSpace = false;
  58893. }
  58894. if (!rootUrl && !files) {
  58895. return _this;
  58896. }
  58897. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58898. var lastDot = rootUrl.lastIndexOf(".");
  58899. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58900. var isDDS = (extension === ".dds");
  58901. if (!files) {
  58902. if (!isDDS && !extensions) {
  58903. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58904. }
  58905. files = [];
  58906. if (extensions) {
  58907. for (var index = 0; index < extensions.length; index++) {
  58908. files.push(rootUrl + extensions[index]);
  58909. }
  58910. }
  58911. }
  58912. _this._files = files;
  58913. if (!_this._texture) {
  58914. if (!scene.useDelayedTextureLoading) {
  58915. if (prefiltered) {
  58916. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58917. }
  58918. else {
  58919. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58920. }
  58921. }
  58922. else {
  58923. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58924. }
  58925. }
  58926. else if (onLoad) {
  58927. if (_this._texture.isReady) {
  58928. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58929. }
  58930. else {
  58931. _this._texture.onLoadedObservable.add(onLoad);
  58932. }
  58933. }
  58934. return _this;
  58935. }
  58936. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58937. get: function () {
  58938. return this._boundingBoxSize;
  58939. },
  58940. /**
  58941. * Gets or sets the size of the bounding box associated with the cube texture
  58942. * When defined, the cubemap will switch to local mode
  58943. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58944. * @example https://www.babylonjs-playground.com/#RNASML
  58945. */
  58946. set: function (value) {
  58947. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58948. return;
  58949. }
  58950. this._boundingBoxSize = value;
  58951. var scene = this.getScene();
  58952. if (scene) {
  58953. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58954. }
  58955. },
  58956. enumerable: true,
  58957. configurable: true
  58958. });
  58959. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58960. var rootUrlKey = "";
  58961. files.forEach(function (url) { return rootUrlKey += url; });
  58962. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58963. };
  58964. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58965. if (forcedExtension === void 0) { forcedExtension = null; }
  58966. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58967. };
  58968. // Methods
  58969. CubeTexture.prototype.delayLoad = function () {
  58970. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58971. return;
  58972. }
  58973. var scene = this.getScene();
  58974. if (!scene) {
  58975. return;
  58976. }
  58977. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58978. this._texture = this._getFromCache(this.url, this._noMipmap);
  58979. if (!this._texture) {
  58980. if (this._prefiltered) {
  58981. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58982. }
  58983. else {
  58984. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58985. }
  58986. }
  58987. };
  58988. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58989. return this._textureMatrix;
  58990. };
  58991. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58992. this._textureMatrix = value;
  58993. };
  58994. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58995. var texture = BABYLON.SerializationHelper.Parse(function () {
  58996. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58997. }, parsedTexture, scene);
  58998. // Local Cubemaps
  58999. if (parsedTexture.boundingBoxPosition) {
  59000. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  59001. }
  59002. if (parsedTexture.boundingBoxSize) {
  59003. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  59004. }
  59005. // Animations
  59006. if (parsedTexture.animations) {
  59007. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  59008. var parsedAnimation = parsedTexture.animations[animationIndex];
  59009. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  59010. }
  59011. }
  59012. return texture;
  59013. };
  59014. CubeTexture.prototype.clone = function () {
  59015. var _this = this;
  59016. return BABYLON.SerializationHelper.Clone(function () {
  59017. var scene = _this.getScene();
  59018. if (!scene) {
  59019. return _this;
  59020. }
  59021. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  59022. }, this);
  59023. };
  59024. return CubeTexture;
  59025. }(BABYLON.BaseTexture));
  59026. BABYLON.CubeTexture = CubeTexture;
  59027. })(BABYLON || (BABYLON = {}));
  59028. //# sourceMappingURL=babylon.cubeTexture.js.map
  59029. "use strict";
  59030. var BABYLON;
  59031. (function (BABYLON) {
  59032. var RenderTargetTexture = /** @class */ (function (_super) {
  59033. __extends(RenderTargetTexture, _super);
  59034. /**
  59035. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  59036. * or used a shadow, depth texture...
  59037. * @param name The friendly name of the texture
  59038. * @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)
  59039. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  59040. * @param generateMipMaps True if mip maps need to be generated after render.
  59041. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  59042. * @param type The type of the buffer in the RTT (int, half float, float...)
  59043. * @param isCube True if a cube texture needs to be created
  59044. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  59045. * @param generateDepthBuffer True to generate a depth buffer
  59046. * @param generateStencilBuffer True to generate a stencil buffer
  59047. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  59048. */
  59049. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  59050. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  59051. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59052. if (isCube === void 0) { isCube = false; }
  59053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59054. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59055. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  59056. if (isMulti === void 0) { isMulti = false; }
  59057. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59058. _this.isCube = isCube;
  59059. /**
  59060. * Use this list to define the list of mesh you want to render.
  59061. */
  59062. _this.renderList = new Array();
  59063. _this.renderParticles = true;
  59064. _this.renderSprites = false;
  59065. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  59066. _this.ignoreCameraViewport = false;
  59067. // Events
  59068. /**
  59069. * An event triggered when the texture is unbind.
  59070. * @type {BABYLON.Observable}
  59071. */
  59072. _this.onBeforeBindObservable = new BABYLON.Observable();
  59073. /**
  59074. * An event triggered when the texture is unbind.
  59075. * @type {BABYLON.Observable}
  59076. */
  59077. _this.onAfterUnbindObservable = new BABYLON.Observable();
  59078. /**
  59079. * An event triggered before rendering the texture
  59080. * @type {BABYLON.Observable}
  59081. */
  59082. _this.onBeforeRenderObservable = new BABYLON.Observable();
  59083. /**
  59084. * An event triggered after rendering the texture
  59085. * @type {BABYLON.Observable}
  59086. */
  59087. _this.onAfterRenderObservable = new BABYLON.Observable();
  59088. /**
  59089. * An event triggered after the texture clear
  59090. * @type {BABYLON.Observable}
  59091. */
  59092. _this.onClearObservable = new BABYLON.Observable();
  59093. _this._currentRefreshId = -1;
  59094. _this._refreshRate = 1;
  59095. _this._samples = 1;
  59096. /**
  59097. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  59098. * It must define where the camera used to render the texture is set
  59099. */
  59100. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  59101. scene = _this.getScene();
  59102. if (!scene) {
  59103. return _this;
  59104. }
  59105. _this._engine = scene.getEngine();
  59106. _this.name = name;
  59107. _this.isRenderTarget = true;
  59108. _this._initialSizeParameter = size;
  59109. _this._processSizeParameter(size);
  59110. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  59111. });
  59112. _this._generateMipMaps = generateMipMaps ? true : false;
  59113. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  59114. // Rendering groups
  59115. _this._renderingManager = new BABYLON.RenderingManager(scene);
  59116. if (isMulti) {
  59117. return _this;
  59118. }
  59119. _this._renderTargetOptions = {
  59120. generateMipMaps: generateMipMaps,
  59121. type: type,
  59122. samplingMode: samplingMode,
  59123. generateDepthBuffer: generateDepthBuffer,
  59124. generateStencilBuffer: generateStencilBuffer
  59125. };
  59126. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  59127. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59128. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59129. }
  59130. if (isCube) {
  59131. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  59132. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  59133. _this._textureMatrix = BABYLON.Matrix.Identity();
  59134. }
  59135. else {
  59136. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  59137. }
  59138. return _this;
  59139. }
  59140. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  59141. get: function () {
  59142. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  59143. },
  59144. enumerable: true,
  59145. configurable: true
  59146. });
  59147. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  59148. get: function () {
  59149. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  59150. },
  59151. enumerable: true,
  59152. configurable: true
  59153. });
  59154. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  59155. get: function () {
  59156. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  59157. },
  59158. enumerable: true,
  59159. configurable: true
  59160. });
  59161. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  59162. set: function (callback) {
  59163. if (this._onAfterUnbindObserver) {
  59164. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  59165. }
  59166. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  59167. },
  59168. enumerable: true,
  59169. configurable: true
  59170. });
  59171. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  59172. set: function (callback) {
  59173. if (this._onBeforeRenderObserver) {
  59174. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  59175. }
  59176. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  59177. },
  59178. enumerable: true,
  59179. configurable: true
  59180. });
  59181. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  59182. set: function (callback) {
  59183. if (this._onAfterRenderObserver) {
  59184. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  59185. }
  59186. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  59187. },
  59188. enumerable: true,
  59189. configurable: true
  59190. });
  59191. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  59192. set: function (callback) {
  59193. if (this._onClearObserver) {
  59194. this.onClearObservable.remove(this._onClearObserver);
  59195. }
  59196. this._onClearObserver = this.onClearObservable.add(callback);
  59197. },
  59198. enumerable: true,
  59199. configurable: true
  59200. });
  59201. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  59202. get: function () {
  59203. return this._renderTargetOptions;
  59204. },
  59205. enumerable: true,
  59206. configurable: true
  59207. });
  59208. RenderTargetTexture.prototype._onRatioRescale = function () {
  59209. if (this._sizeRatio) {
  59210. this.resize(this._initialSizeParameter);
  59211. }
  59212. };
  59213. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  59214. get: function () {
  59215. return this._boundingBoxSize;
  59216. },
  59217. /**
  59218. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  59219. * When defined, the cubemap will switch to local mode
  59220. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  59221. * @example https://www.babylonjs-playground.com/#RNASML
  59222. */
  59223. set: function (value) {
  59224. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  59225. return;
  59226. }
  59227. this._boundingBoxSize = value;
  59228. var scene = this.getScene();
  59229. if (scene) {
  59230. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  59231. }
  59232. },
  59233. enumerable: true,
  59234. configurable: true
  59235. });
  59236. /**
  59237. * Creates a depth stencil texture.
  59238. * This is only available in WebGL 2 or with the depth texture extension available.
  59239. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59240. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59241. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59242. */
  59243. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59244. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59245. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59246. if (generateStencil === void 0) { generateStencil = false; }
  59247. if (!this.getScene()) {
  59248. return;
  59249. }
  59250. var engine = this.getScene().getEngine();
  59251. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59252. bilinearFiltering: bilinearFiltering,
  59253. comparisonFunction: comparisonFunction,
  59254. generateStencil: generateStencil,
  59255. isCube: this.isCube
  59256. });
  59257. engine.setFrameBufferDepthStencilTexture(this);
  59258. };
  59259. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59260. if (size.ratio) {
  59261. this._sizeRatio = size.ratio;
  59262. this._size = {
  59263. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59264. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59265. };
  59266. }
  59267. else {
  59268. this._size = size;
  59269. }
  59270. };
  59271. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59272. get: function () {
  59273. return this._samples;
  59274. },
  59275. set: function (value) {
  59276. if (this._samples === value) {
  59277. return;
  59278. }
  59279. var scene = this.getScene();
  59280. if (!scene) {
  59281. return;
  59282. }
  59283. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59284. },
  59285. enumerable: true,
  59286. configurable: true
  59287. });
  59288. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59289. this._currentRefreshId = -1;
  59290. };
  59291. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59292. get: function () {
  59293. return this._refreshRate;
  59294. },
  59295. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59296. set: function (value) {
  59297. this._refreshRate = value;
  59298. this.resetRefreshCounter();
  59299. },
  59300. enumerable: true,
  59301. configurable: true
  59302. });
  59303. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59304. if (!this._postProcessManager) {
  59305. var scene = this.getScene();
  59306. if (!scene) {
  59307. return;
  59308. }
  59309. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59310. this._postProcesses = new Array();
  59311. }
  59312. this._postProcesses.push(postProcess);
  59313. this._postProcesses[0].autoClear = false;
  59314. };
  59315. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59316. if (!this._postProcesses) {
  59317. return;
  59318. }
  59319. if (dispose) {
  59320. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59321. var postProcess = _a[_i];
  59322. postProcess.dispose();
  59323. }
  59324. }
  59325. this._postProcesses = [];
  59326. };
  59327. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59328. if (!this._postProcesses) {
  59329. return;
  59330. }
  59331. var index = this._postProcesses.indexOf(postProcess);
  59332. if (index === -1) {
  59333. return;
  59334. }
  59335. this._postProcesses.splice(index, 1);
  59336. if (this._postProcesses.length > 0) {
  59337. this._postProcesses[0].autoClear = false;
  59338. }
  59339. };
  59340. RenderTargetTexture.prototype._shouldRender = function () {
  59341. if (this._currentRefreshId === -1) {
  59342. this._currentRefreshId = 1;
  59343. return true;
  59344. }
  59345. if (this.refreshRate === this._currentRefreshId) {
  59346. this._currentRefreshId = 1;
  59347. return true;
  59348. }
  59349. this._currentRefreshId++;
  59350. return false;
  59351. };
  59352. RenderTargetTexture.prototype.getRenderSize = function () {
  59353. if (this._size.width) {
  59354. return this._size.width;
  59355. }
  59356. return this._size;
  59357. };
  59358. RenderTargetTexture.prototype.getRenderWidth = function () {
  59359. if (this._size.width) {
  59360. return this._size.width;
  59361. }
  59362. return this._size;
  59363. };
  59364. RenderTargetTexture.prototype.getRenderHeight = function () {
  59365. if (this._size.width) {
  59366. return this._size.height;
  59367. }
  59368. return this._size;
  59369. };
  59370. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59371. get: function () {
  59372. return true;
  59373. },
  59374. enumerable: true,
  59375. configurable: true
  59376. });
  59377. RenderTargetTexture.prototype.scale = function (ratio) {
  59378. var newSize = this.getRenderSize() * ratio;
  59379. this.resize(newSize);
  59380. };
  59381. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59382. if (this.isCube) {
  59383. return this._textureMatrix;
  59384. }
  59385. return _super.prototype.getReflectionTextureMatrix.call(this);
  59386. };
  59387. RenderTargetTexture.prototype.resize = function (size) {
  59388. this.releaseInternalTexture();
  59389. var scene = this.getScene();
  59390. if (!scene) {
  59391. return;
  59392. }
  59393. this._processSizeParameter(size);
  59394. if (this.isCube) {
  59395. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59396. }
  59397. else {
  59398. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59399. }
  59400. };
  59401. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59402. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59403. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59404. var scene = this.getScene();
  59405. if (!scene) {
  59406. return;
  59407. }
  59408. var engine = scene.getEngine();
  59409. if (this.useCameraPostProcesses !== undefined) {
  59410. useCameraPostProcess = this.useCameraPostProcesses;
  59411. }
  59412. if (this._waitingRenderList) {
  59413. this.renderList = [];
  59414. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59415. var id = this._waitingRenderList[index];
  59416. var mesh_1 = scene.getMeshByID(id);
  59417. if (mesh_1) {
  59418. this.renderList.push(mesh_1);
  59419. }
  59420. }
  59421. delete this._waitingRenderList;
  59422. }
  59423. // Is predicate defined?
  59424. if (this.renderListPredicate) {
  59425. if (this.renderList) {
  59426. this.renderList.splice(0); // Clear previous renderList
  59427. }
  59428. else {
  59429. this.renderList = [];
  59430. }
  59431. var scene = this.getScene();
  59432. if (!scene) {
  59433. return;
  59434. }
  59435. var sceneMeshes = scene.meshes;
  59436. for (var index = 0; index < sceneMeshes.length; index++) {
  59437. var mesh = sceneMeshes[index];
  59438. if (this.renderListPredicate(mesh)) {
  59439. this.renderList.push(mesh);
  59440. }
  59441. }
  59442. }
  59443. this.onBeforeBindObservable.notifyObservers(this);
  59444. // Set custom projection.
  59445. // Needs to be before binding to prevent changing the aspect ratio.
  59446. var camera;
  59447. if (this.activeCamera) {
  59448. camera = this.activeCamera;
  59449. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59450. if (this.activeCamera !== scene.activeCamera) {
  59451. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59452. }
  59453. }
  59454. else {
  59455. camera = scene.activeCamera;
  59456. if (camera) {
  59457. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59458. }
  59459. }
  59460. // Prepare renderingManager
  59461. this._renderingManager.reset();
  59462. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59463. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59464. var sceneRenderId = scene.getRenderId();
  59465. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59466. var mesh = currentRenderList[meshIndex];
  59467. if (mesh) {
  59468. if (!mesh.isReady(this.refreshRate === 0)) {
  59469. this.resetRefreshCounter();
  59470. continue;
  59471. }
  59472. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59473. var isMasked = void 0;
  59474. if (!this.renderList && camera) {
  59475. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59476. }
  59477. else {
  59478. isMasked = false;
  59479. }
  59480. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59481. mesh._activate(sceneRenderId);
  59482. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59483. var subMesh = mesh.subMeshes[subIndex];
  59484. scene._activeIndices.addCount(subMesh.indexCount, false);
  59485. this._renderingManager.dispatch(subMesh, mesh);
  59486. }
  59487. }
  59488. }
  59489. }
  59490. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59491. var particleSystem = scene.particleSystems[particleIndex];
  59492. var emitter = particleSystem.emitter;
  59493. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59494. continue;
  59495. }
  59496. if (currentRenderList.indexOf(emitter) >= 0) {
  59497. this._renderingManager.dispatchParticles(particleSystem);
  59498. }
  59499. }
  59500. if (this.isCube) {
  59501. for (var face = 0; face < 6; face++) {
  59502. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59503. scene.incrementRenderId();
  59504. scene.resetCachedMaterial();
  59505. }
  59506. }
  59507. else {
  59508. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59509. }
  59510. this.onAfterUnbindObservable.notifyObservers(this);
  59511. if (scene.activeCamera) {
  59512. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59513. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59514. }
  59515. engine.setViewport(scene.activeCamera.viewport);
  59516. }
  59517. scene.resetCachedMaterial();
  59518. };
  59519. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59520. var minimum = 128;
  59521. var x = renderDimension * scale;
  59522. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59523. // Ensure we don't exceed the render dimension (while staying POT)
  59524. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59525. };
  59526. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59527. var _this = this;
  59528. if (!this._texture) {
  59529. return;
  59530. }
  59531. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59532. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59533. });
  59534. };
  59535. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59536. var scene = this.getScene();
  59537. if (!scene) {
  59538. return;
  59539. }
  59540. var engine = scene.getEngine();
  59541. if (!this._texture) {
  59542. return;
  59543. }
  59544. // Bind
  59545. if (this._postProcessManager) {
  59546. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59547. }
  59548. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59549. if (this._texture) {
  59550. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59551. }
  59552. }
  59553. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59554. // Clear
  59555. if (this.onClearObservable.hasObservers()) {
  59556. this.onClearObservable.notifyObservers(engine);
  59557. }
  59558. else {
  59559. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59560. }
  59561. if (!this._doNotChangeAspectRatio) {
  59562. scene.updateTransformMatrix(true);
  59563. }
  59564. // Render
  59565. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59566. if (this._postProcessManager) {
  59567. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59568. }
  59569. else if (useCameraPostProcess) {
  59570. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59571. }
  59572. if (!this._doNotChangeAspectRatio) {
  59573. scene.updateTransformMatrix(true);
  59574. }
  59575. // Dump ?
  59576. if (dumpForDebug) {
  59577. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59578. }
  59579. // Unbind
  59580. if (!this.isCube || faceIndex === 5) {
  59581. if (this.isCube) {
  59582. if (faceIndex === 5) {
  59583. engine.generateMipMapsForCubemap(this._texture);
  59584. }
  59585. }
  59586. this.unbindFrameBuffer(engine, faceIndex);
  59587. }
  59588. else {
  59589. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59590. }
  59591. };
  59592. /**
  59593. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59594. * This allowed control for front to back rendering or reversly depending of the special needs.
  59595. *
  59596. * @param renderingGroupId The rendering group id corresponding to its index
  59597. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59598. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59599. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59600. */
  59601. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59602. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59603. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59604. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59605. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59606. };
  59607. /**
  59608. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59609. *
  59610. * @param renderingGroupId The rendering group id corresponding to its index
  59611. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59612. */
  59613. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59614. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59615. };
  59616. RenderTargetTexture.prototype.clone = function () {
  59617. var textureSize = this.getSize();
  59618. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59619. // Base texture
  59620. newTexture.hasAlpha = this.hasAlpha;
  59621. newTexture.level = this.level;
  59622. // RenderTarget Texture
  59623. newTexture.coordinatesMode = this.coordinatesMode;
  59624. if (this.renderList) {
  59625. newTexture.renderList = this.renderList.slice(0);
  59626. }
  59627. return newTexture;
  59628. };
  59629. RenderTargetTexture.prototype.serialize = function () {
  59630. if (!this.name) {
  59631. return null;
  59632. }
  59633. var serializationObject = _super.prototype.serialize.call(this);
  59634. serializationObject.renderTargetSize = this.getRenderSize();
  59635. serializationObject.renderList = [];
  59636. if (this.renderList) {
  59637. for (var index = 0; index < this.renderList.length; index++) {
  59638. serializationObject.renderList.push(this.renderList[index].id);
  59639. }
  59640. }
  59641. return serializationObject;
  59642. };
  59643. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59644. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59645. var objBuffer = this.getInternalTexture();
  59646. var scene = this.getScene();
  59647. if (objBuffer && scene) {
  59648. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59649. }
  59650. };
  59651. RenderTargetTexture.prototype.dispose = function () {
  59652. if (this._postProcessManager) {
  59653. this._postProcessManager.dispose();
  59654. this._postProcessManager = null;
  59655. }
  59656. this.clearPostProcesses(true);
  59657. if (this._resizeObserver) {
  59658. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59659. this._resizeObserver = null;
  59660. }
  59661. this.renderList = null;
  59662. // Remove from custom render targets
  59663. var scene = this.getScene();
  59664. if (!scene) {
  59665. return;
  59666. }
  59667. var index = scene.customRenderTargets.indexOf(this);
  59668. if (index >= 0) {
  59669. scene.customRenderTargets.splice(index, 1);
  59670. }
  59671. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59672. var camera = _a[_i];
  59673. index = camera.customRenderTargets.indexOf(this);
  59674. if (index >= 0) {
  59675. camera.customRenderTargets.splice(index, 1);
  59676. }
  59677. }
  59678. _super.prototype.dispose.call(this);
  59679. };
  59680. RenderTargetTexture.prototype._rebuild = function () {
  59681. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59682. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59683. }
  59684. if (this._postProcessManager) {
  59685. this._postProcessManager._rebuild();
  59686. }
  59687. };
  59688. /**
  59689. * Clear the info related to rendering groups preventing retention point in material dispose.
  59690. */
  59691. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59692. if (this._renderingManager) {
  59693. this._renderingManager.freeRenderingGroups();
  59694. }
  59695. };
  59696. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59697. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59698. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59699. return RenderTargetTexture;
  59700. }(BABYLON.Texture));
  59701. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59702. })(BABYLON || (BABYLON = {}));
  59703. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59704. "use strict";
  59705. var BABYLON;
  59706. (function (BABYLON) {
  59707. ;
  59708. var MultiRenderTarget = /** @class */ (function (_super) {
  59709. __extends(MultiRenderTarget, _super);
  59710. function MultiRenderTarget(name, size, count, scene, options) {
  59711. var _this = this;
  59712. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59713. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59714. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59715. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59716. _this._engine = scene.getEngine();
  59717. if (!_this.isSupported) {
  59718. _this.dispose();
  59719. return;
  59720. }
  59721. var types = [];
  59722. var samplingModes = [];
  59723. for (var i = 0; i < count; i++) {
  59724. if (options && options.types && options.types[i] !== undefined) {
  59725. types.push(options.types[i]);
  59726. }
  59727. else {
  59728. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59729. }
  59730. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59731. samplingModes.push(options.samplingModes[i]);
  59732. }
  59733. else {
  59734. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59735. }
  59736. }
  59737. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59738. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59739. _this._size = size;
  59740. _this._multiRenderTargetOptions = {
  59741. samplingModes: samplingModes,
  59742. generateMipMaps: generateMipMaps,
  59743. generateDepthBuffer: generateDepthBuffer,
  59744. generateStencilBuffer: generateStencilBuffer,
  59745. generateDepthTexture: generateDepthTexture,
  59746. types: types,
  59747. textureCount: count
  59748. };
  59749. _this._createInternalTextures();
  59750. _this._createTextures();
  59751. return _this;
  59752. }
  59753. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59754. get: function () {
  59755. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59756. },
  59757. enumerable: true,
  59758. configurable: true
  59759. });
  59760. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59761. get: function () {
  59762. return this._textures;
  59763. },
  59764. enumerable: true,
  59765. configurable: true
  59766. });
  59767. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59768. get: function () {
  59769. return this._textures[this._textures.length - 1];
  59770. },
  59771. enumerable: true,
  59772. configurable: true
  59773. });
  59774. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59775. set: function (wrap) {
  59776. if (this._textures) {
  59777. for (var i = 0; i < this._textures.length; i++) {
  59778. this._textures[i].wrapU = wrap;
  59779. }
  59780. }
  59781. },
  59782. enumerable: true,
  59783. configurable: true
  59784. });
  59785. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59786. set: function (wrap) {
  59787. if (this._textures) {
  59788. for (var i = 0; i < this._textures.length; i++) {
  59789. this._textures[i].wrapV = wrap;
  59790. }
  59791. }
  59792. },
  59793. enumerable: true,
  59794. configurable: true
  59795. });
  59796. MultiRenderTarget.prototype._rebuild = function () {
  59797. this.releaseInternalTextures();
  59798. this._createInternalTextures();
  59799. for (var i = 0; i < this._internalTextures.length; i++) {
  59800. var texture = this._textures[i];
  59801. texture._texture = this._internalTextures[i];
  59802. }
  59803. // Keeps references to frame buffer and stencil/depth buffer
  59804. this._texture = this._internalTextures[0];
  59805. };
  59806. MultiRenderTarget.prototype._createInternalTextures = function () {
  59807. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59808. };
  59809. MultiRenderTarget.prototype._createTextures = function () {
  59810. this._textures = [];
  59811. for (var i = 0; i < this._internalTextures.length; i++) {
  59812. var texture = new BABYLON.Texture(null, this.getScene());
  59813. texture._texture = this._internalTextures[i];
  59814. this._textures.push(texture);
  59815. }
  59816. // Keeps references to frame buffer and stencil/depth buffer
  59817. this._texture = this._internalTextures[0];
  59818. };
  59819. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59820. get: function () {
  59821. return this._samples;
  59822. },
  59823. set: function (value) {
  59824. if (this._samples === value) {
  59825. return;
  59826. }
  59827. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59828. },
  59829. enumerable: true,
  59830. configurable: true
  59831. });
  59832. MultiRenderTarget.prototype.resize = function (size) {
  59833. this.releaseInternalTextures();
  59834. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59835. this._createInternalTextures();
  59836. };
  59837. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59838. var _this = this;
  59839. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59840. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59841. });
  59842. };
  59843. MultiRenderTarget.prototype.dispose = function () {
  59844. this.releaseInternalTextures();
  59845. _super.prototype.dispose.call(this);
  59846. };
  59847. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59848. if (!this._internalTextures) {
  59849. return;
  59850. }
  59851. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59852. if (this._internalTextures[i] !== undefined) {
  59853. this._internalTextures[i].dispose();
  59854. this._internalTextures.splice(i, 1);
  59855. }
  59856. }
  59857. };
  59858. return MultiRenderTarget;
  59859. }(BABYLON.RenderTargetTexture));
  59860. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59861. })(BABYLON || (BABYLON = {}));
  59862. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59863. "use strict";
  59864. var BABYLON;
  59865. (function (BABYLON) {
  59866. var MirrorTexture = /** @class */ (function (_super) {
  59867. __extends(MirrorTexture, _super);
  59868. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59869. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59870. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59871. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59872. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59873. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59874. _this._transformMatrix = BABYLON.Matrix.Zero();
  59875. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59876. _this._adaptiveBlurKernel = 0;
  59877. _this._blurKernelX = 0;
  59878. _this._blurKernelY = 0;
  59879. _this._blurRatio = 1.0;
  59880. _this.ignoreCameraViewport = true;
  59881. _this.onBeforeRenderObservable.add(function () {
  59882. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59883. _this._savedViewMatrix = scene.getViewMatrix();
  59884. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59885. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59886. scene.clipPlane = _this.mirrorPlane;
  59887. scene.getEngine().cullBackFaces = false;
  59888. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59889. });
  59890. _this.onAfterRenderObservable.add(function () {
  59891. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59892. scene.getEngine().cullBackFaces = true;
  59893. scene._mirroredCameraPosition = null;
  59894. delete scene.clipPlane;
  59895. });
  59896. return _this;
  59897. }
  59898. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59899. get: function () {
  59900. return this._blurRatio;
  59901. },
  59902. set: function (value) {
  59903. if (this._blurRatio === value) {
  59904. return;
  59905. }
  59906. this._blurRatio = value;
  59907. this._preparePostProcesses();
  59908. },
  59909. enumerable: true,
  59910. configurable: true
  59911. });
  59912. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59913. set: function (value) {
  59914. this._adaptiveBlurKernel = value;
  59915. this._autoComputeBlurKernel();
  59916. },
  59917. enumerable: true,
  59918. configurable: true
  59919. });
  59920. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59921. set: function (value) {
  59922. this.blurKernelX = value;
  59923. this.blurKernelY = value;
  59924. },
  59925. enumerable: true,
  59926. configurable: true
  59927. });
  59928. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59929. get: function () {
  59930. return this._blurKernelX;
  59931. },
  59932. set: function (value) {
  59933. if (this._blurKernelX === value) {
  59934. return;
  59935. }
  59936. this._blurKernelX = value;
  59937. this._preparePostProcesses();
  59938. },
  59939. enumerable: true,
  59940. configurable: true
  59941. });
  59942. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59943. get: function () {
  59944. return this._blurKernelY;
  59945. },
  59946. set: function (value) {
  59947. if (this._blurKernelY === value) {
  59948. return;
  59949. }
  59950. this._blurKernelY = value;
  59951. this._preparePostProcesses();
  59952. },
  59953. enumerable: true,
  59954. configurable: true
  59955. });
  59956. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59957. var engine = this.getScene().getEngine();
  59958. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59959. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59960. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59961. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59962. };
  59963. MirrorTexture.prototype._onRatioRescale = function () {
  59964. if (this._sizeRatio) {
  59965. this.resize(this._initialSizeParameter);
  59966. if (!this._adaptiveBlurKernel) {
  59967. this._preparePostProcesses();
  59968. }
  59969. }
  59970. if (this._adaptiveBlurKernel) {
  59971. this._autoComputeBlurKernel();
  59972. }
  59973. };
  59974. MirrorTexture.prototype._preparePostProcesses = function () {
  59975. this.clearPostProcesses(true);
  59976. if (this._blurKernelX && this._blurKernelY) {
  59977. var engine = this.getScene().getEngine();
  59978. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59979. 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);
  59980. this._blurX.autoClear = false;
  59981. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59982. this._blurX.inputTexture = this._texture;
  59983. }
  59984. else {
  59985. this._blurX.alwaysForcePOT = true;
  59986. }
  59987. 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);
  59988. this._blurY.autoClear = false;
  59989. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59990. this.addPostProcess(this._blurX);
  59991. this.addPostProcess(this._blurY);
  59992. }
  59993. else {
  59994. if (this._blurY) {
  59995. this.removePostProcess(this._blurY);
  59996. this._blurY.dispose();
  59997. this._blurY = null;
  59998. }
  59999. if (this._blurX) {
  60000. this.removePostProcess(this._blurX);
  60001. this._blurX.dispose();
  60002. this._blurX = null;
  60003. }
  60004. }
  60005. };
  60006. MirrorTexture.prototype.clone = function () {
  60007. var scene = this.getScene();
  60008. if (!scene) {
  60009. return this;
  60010. }
  60011. var textureSize = this.getSize();
  60012. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  60013. // Base texture
  60014. newTexture.hasAlpha = this.hasAlpha;
  60015. newTexture.level = this.level;
  60016. // Mirror Texture
  60017. newTexture.mirrorPlane = this.mirrorPlane.clone();
  60018. if (this.renderList) {
  60019. newTexture.renderList = this.renderList.slice(0);
  60020. }
  60021. return newTexture;
  60022. };
  60023. MirrorTexture.prototype.serialize = function () {
  60024. if (!this.name) {
  60025. return null;
  60026. }
  60027. var serializationObject = _super.prototype.serialize.call(this);
  60028. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  60029. return serializationObject;
  60030. };
  60031. return MirrorTexture;
  60032. }(BABYLON.RenderTargetTexture));
  60033. BABYLON.MirrorTexture = MirrorTexture;
  60034. })(BABYLON || (BABYLON = {}));
  60035. //# sourceMappingURL=babylon.mirrorTexture.js.map
  60036. "use strict";
  60037. var BABYLON;
  60038. (function (BABYLON) {
  60039. /**
  60040. * Creates a refraction texture used by refraction channel of the standard material.
  60041. * @param name the texture name
  60042. * @param size size of the underlying texture
  60043. * @param scene root scene
  60044. */
  60045. var RefractionTexture = /** @class */ (function (_super) {
  60046. __extends(RefractionTexture, _super);
  60047. function RefractionTexture(name, size, scene, generateMipMaps) {
  60048. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  60049. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  60050. _this.depth = 2.0;
  60051. _this.onBeforeRenderObservable.add(function () {
  60052. scene.clipPlane = _this.refractionPlane;
  60053. });
  60054. _this.onAfterRenderObservable.add(function () {
  60055. delete scene.clipPlane;
  60056. });
  60057. return _this;
  60058. }
  60059. RefractionTexture.prototype.clone = function () {
  60060. var scene = this.getScene();
  60061. if (!scene) {
  60062. return this;
  60063. }
  60064. var textureSize = this.getSize();
  60065. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  60066. // Base texture
  60067. newTexture.hasAlpha = this.hasAlpha;
  60068. newTexture.level = this.level;
  60069. // Refraction Texture
  60070. newTexture.refractionPlane = this.refractionPlane.clone();
  60071. if (this.renderList) {
  60072. newTexture.renderList = this.renderList.slice(0);
  60073. }
  60074. newTexture.depth = this.depth;
  60075. return newTexture;
  60076. };
  60077. RefractionTexture.prototype.serialize = function () {
  60078. if (!this.name) {
  60079. return null;
  60080. }
  60081. var serializationObject = _super.prototype.serialize.call(this);
  60082. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  60083. serializationObject.depth = this.depth;
  60084. return serializationObject;
  60085. };
  60086. return RefractionTexture;
  60087. }(BABYLON.RenderTargetTexture));
  60088. BABYLON.RefractionTexture = RefractionTexture;
  60089. })(BABYLON || (BABYLON = {}));
  60090. //# sourceMappingURL=babylon.refractionTexture.js.map
  60091. "use strict";
  60092. var BABYLON;
  60093. (function (BABYLON) {
  60094. /**
  60095. * A class extending {BABYLON.Texture} allowing drawing on a texture
  60096. * @see http://doc.babylonjs.com/how_to/dynamictexture
  60097. */
  60098. var DynamicTexture = /** @class */ (function (_super) {
  60099. __extends(DynamicTexture, _super);
  60100. /**
  60101. * Creates a {BABYLON.DynamicTexture}
  60102. * @param name defines the name of the texture
  60103. * @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
  60104. * @param scene defines the scene where you want the texture
  60105. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  60106. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  60107. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  60108. */
  60109. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  60110. if (scene === void 0) { scene = null; }
  60111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60112. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  60113. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  60114. _this.name = name;
  60115. _this._engine = _this.getScene().getEngine();
  60116. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60117. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60118. _this._generateMipMaps = generateMipMaps;
  60119. if (options.getContext) {
  60120. _this._canvas = options;
  60121. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60122. }
  60123. else {
  60124. _this._canvas = document.createElement("canvas");
  60125. if (options.width) {
  60126. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  60127. }
  60128. else {
  60129. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  60130. }
  60131. }
  60132. var textureSize = _this.getSize();
  60133. _this._canvas.width = textureSize.width;
  60134. _this._canvas.height = textureSize.height;
  60135. _this._context = _this._canvas.getContext("2d");
  60136. return _this;
  60137. }
  60138. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  60139. /**
  60140. * Gets the current state of canRescale
  60141. */
  60142. get: function () {
  60143. return true;
  60144. },
  60145. enumerable: true,
  60146. configurable: true
  60147. });
  60148. DynamicTexture.prototype._recreate = function (textureSize) {
  60149. this._canvas.width = textureSize.width;
  60150. this._canvas.height = textureSize.height;
  60151. this.releaseInternalTexture();
  60152. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  60153. };
  60154. /**
  60155. * Scales the texture
  60156. * @param ratio the scale factor to apply to both width and height
  60157. */
  60158. DynamicTexture.prototype.scale = function (ratio) {
  60159. var textureSize = this.getSize();
  60160. textureSize.width *= ratio;
  60161. textureSize.height *= ratio;
  60162. this._recreate(textureSize);
  60163. };
  60164. /**
  60165. * Resizes the texture
  60166. * @param width the new width
  60167. * @param height the new height
  60168. */
  60169. DynamicTexture.prototype.scaleTo = function (width, height) {
  60170. var textureSize = this.getSize();
  60171. textureSize.width = width;
  60172. textureSize.height = height;
  60173. this._recreate(textureSize);
  60174. };
  60175. /**
  60176. * Gets the context of the canvas used by the texture
  60177. * @returns the canvas context of the dynamic texture
  60178. */
  60179. DynamicTexture.prototype.getContext = function () {
  60180. return this._context;
  60181. };
  60182. /**
  60183. * Clears the texture
  60184. */
  60185. DynamicTexture.prototype.clear = function () {
  60186. var size = this.getSize();
  60187. this._context.fillRect(0, 0, size.width, size.height);
  60188. };
  60189. /**
  60190. * Updates the texture
  60191. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60192. */
  60193. DynamicTexture.prototype.update = function (invertY) {
  60194. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  60195. };
  60196. /**
  60197. * Draws text onto the texture
  60198. * @param text defines the text to be drawn
  60199. * @param x defines the placement of the text from the left
  60200. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  60201. * @param font defines the font to be used with font-style, font-size, font-name
  60202. * @param color defines the color used for the text
  60203. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  60204. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  60205. * @param update defines whether texture is immediately update (default is true)
  60206. */
  60207. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  60208. if (update === void 0) { update = true; }
  60209. var size = this.getSize();
  60210. if (clearColor) {
  60211. this._context.fillStyle = clearColor;
  60212. this._context.fillRect(0, 0, size.width, size.height);
  60213. }
  60214. this._context.font = font;
  60215. if (x === null || x === undefined) {
  60216. var textSize = this._context.measureText(text);
  60217. x = (size.width - textSize.width) / 2;
  60218. }
  60219. if (y === null || y === undefined) {
  60220. var fontSize = parseInt((font.replace(/\D/g, '')));
  60221. ;
  60222. y = (size.height / 2) + (fontSize / 3.65);
  60223. }
  60224. this._context.fillStyle = color;
  60225. this._context.fillText(text, x, y);
  60226. if (update) {
  60227. this.update(invertY);
  60228. }
  60229. };
  60230. /**
  60231. * Clones the texture
  60232. * @returns the clone of the texture.
  60233. */
  60234. DynamicTexture.prototype.clone = function () {
  60235. var scene = this.getScene();
  60236. if (!scene) {
  60237. return this;
  60238. }
  60239. var textureSize = this.getSize();
  60240. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  60241. // Base texture
  60242. newTexture.hasAlpha = this.hasAlpha;
  60243. newTexture.level = this.level;
  60244. // Dynamic Texture
  60245. newTexture.wrapU = this.wrapU;
  60246. newTexture.wrapV = this.wrapV;
  60247. return newTexture;
  60248. };
  60249. /** @ignore */
  60250. DynamicTexture.prototype._rebuild = function () {
  60251. this.update();
  60252. };
  60253. return DynamicTexture;
  60254. }(BABYLON.Texture));
  60255. BABYLON.DynamicTexture = DynamicTexture;
  60256. })(BABYLON || (BABYLON = {}));
  60257. //# sourceMappingURL=babylon.dynamicTexture.js.map
  60258. "use strict";
  60259. var BABYLON;
  60260. (function (BABYLON) {
  60261. var VideoTexture = /** @class */ (function (_super) {
  60262. __extends(VideoTexture, _super);
  60263. /**
  60264. * Creates a video texture.
  60265. * Sample : https://doc.babylonjs.com/how_to/video_texture
  60266. * @param {string | null} name optional name, will detect from video source, if not defined
  60267. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  60268. * @param {BABYLON.Scene} scene is obviously the current scene.
  60269. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  60270. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  60271. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  60272. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  60273. */
  60274. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  60275. if (generateMipMaps === void 0) { generateMipMaps = false; }
  60276. if (invertY === void 0) { invertY = false; }
  60277. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60278. if (settings === void 0) { settings = {
  60279. autoPlay: true,
  60280. loop: true,
  60281. autoUpdateTexture: true,
  60282. }; }
  60283. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60284. _this._createInternalTexture = function () {
  60285. if (_this._texture != null) {
  60286. return;
  60287. }
  60288. if (!_this._engine.needPOTTextures ||
  60289. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60290. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60291. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60292. }
  60293. else {
  60294. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60295. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60296. _this._generateMipMaps = false;
  60297. }
  60298. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60299. _this._texture.isReady = true;
  60300. _this._updateInternalTexture();
  60301. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60302. _this.onLoadObservable.notifyObservers(_this);
  60303. }
  60304. };
  60305. _this.reset = function () {
  60306. if (_this._texture == null) {
  60307. return;
  60308. }
  60309. _this._texture.dispose();
  60310. _this._texture = null;
  60311. };
  60312. _this._updateInternalTexture = function (e) {
  60313. if (_this._texture == null || !_this._texture.isReady) {
  60314. return;
  60315. }
  60316. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60317. return;
  60318. }
  60319. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60320. };
  60321. _this._engine = _this.getScene().getEngine();
  60322. _this._generateMipMaps = generateMipMaps;
  60323. _this._samplingMode = samplingMode;
  60324. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60325. _this.name = name || _this._getName(src);
  60326. _this.video = _this._getVideo(src);
  60327. if (settings.autoPlay !== undefined) {
  60328. _this.video.autoplay = settings.autoPlay;
  60329. }
  60330. if (settings.loop !== undefined) {
  60331. _this.video.loop = settings.loop;
  60332. }
  60333. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60334. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60335. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60336. _this.video.addEventListener("emptied", _this.reset);
  60337. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60338. _this._createInternalTexture();
  60339. }
  60340. return _this;
  60341. }
  60342. VideoTexture.prototype._getName = function (src) {
  60343. if (src instanceof HTMLVideoElement) {
  60344. return src.currentSrc;
  60345. }
  60346. if (typeof src === "object") {
  60347. return src.toString();
  60348. }
  60349. return src;
  60350. };
  60351. ;
  60352. VideoTexture.prototype._getVideo = function (src) {
  60353. if (src instanceof HTMLVideoElement) {
  60354. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60355. return src;
  60356. }
  60357. var video = document.createElement("video");
  60358. if (typeof src === "string") {
  60359. BABYLON.Tools.SetCorsBehavior(src, video);
  60360. video.src = src;
  60361. }
  60362. else {
  60363. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60364. src.forEach(function (url) {
  60365. var source = document.createElement("source");
  60366. source.src = url;
  60367. video.appendChild(source);
  60368. });
  60369. }
  60370. return video;
  60371. };
  60372. ;
  60373. /**
  60374. * Internal method to initiate `update`.
  60375. */
  60376. VideoTexture.prototype._rebuild = function () {
  60377. this.update();
  60378. };
  60379. /**
  60380. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60381. */
  60382. VideoTexture.prototype.update = function () {
  60383. if (!this.autoUpdateTexture) {
  60384. // Expecting user to call `updateTexture` manually
  60385. return;
  60386. }
  60387. this.updateTexture(true);
  60388. };
  60389. /**
  60390. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60391. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60392. */
  60393. VideoTexture.prototype.updateTexture = function (isVisible) {
  60394. if (!isVisible) {
  60395. return;
  60396. }
  60397. if (this.video.paused) {
  60398. return;
  60399. }
  60400. this._updateInternalTexture();
  60401. };
  60402. /**
  60403. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60404. * @param url New url.
  60405. */
  60406. VideoTexture.prototype.updateURL = function (url) {
  60407. this.video.src = url;
  60408. };
  60409. VideoTexture.prototype.dispose = function () {
  60410. _super.prototype.dispose.call(this);
  60411. this.video.removeEventListener("canplay", this._createInternalTexture);
  60412. this.video.removeEventListener("paused", this._updateInternalTexture);
  60413. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60414. this.video.removeEventListener("emptied", this.reset);
  60415. this.video.pause();
  60416. };
  60417. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60418. var video = document.createElement("video");
  60419. var constraintsDeviceId;
  60420. if (constraints && constraints.deviceId) {
  60421. constraintsDeviceId = {
  60422. exact: constraints.deviceId,
  60423. };
  60424. }
  60425. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60426. if (navigator.mediaDevices) {
  60427. navigator.mediaDevices.getUserMedia({ video: constraints })
  60428. .then(function (stream) {
  60429. if (video.mozSrcObject !== undefined) {
  60430. // hack for Firefox < 19
  60431. video.mozSrcObject = stream;
  60432. }
  60433. else {
  60434. video.srcObject = stream;
  60435. }
  60436. var onPlaying = function () {
  60437. if (onReady) {
  60438. onReady(new VideoTexture("video", video, scene, true, true));
  60439. }
  60440. video.removeEventListener("playing", onPlaying);
  60441. };
  60442. video.addEventListener("playing", onPlaying);
  60443. video.play();
  60444. })
  60445. .catch(function (err) {
  60446. BABYLON.Tools.Error(err.name);
  60447. });
  60448. }
  60449. else {
  60450. navigator.getUserMedia =
  60451. navigator.getUserMedia ||
  60452. navigator.webkitGetUserMedia ||
  60453. navigator.mozGetUserMedia ||
  60454. navigator.msGetUserMedia;
  60455. if (navigator.getUserMedia) {
  60456. navigator.getUserMedia({
  60457. video: {
  60458. deviceId: constraintsDeviceId,
  60459. width: {
  60460. min: (constraints && constraints.minWidth) || 256,
  60461. max: (constraints && constraints.maxWidth) || 640,
  60462. },
  60463. height: {
  60464. min: (constraints && constraints.minHeight) || 256,
  60465. max: (constraints && constraints.maxHeight) || 480,
  60466. },
  60467. },
  60468. }, function (stream) {
  60469. if (video.mozSrcObject !== undefined) {
  60470. // hack for Firefox < 19
  60471. video.mozSrcObject = stream;
  60472. }
  60473. else {
  60474. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60475. }
  60476. video.play();
  60477. if (onReady) {
  60478. onReady(new VideoTexture("video", video, scene, true, true));
  60479. }
  60480. }, function (e) {
  60481. BABYLON.Tools.Error(e.name);
  60482. });
  60483. }
  60484. }
  60485. };
  60486. return VideoTexture;
  60487. }(BABYLON.Texture));
  60488. BABYLON.VideoTexture = VideoTexture;
  60489. })(BABYLON || (BABYLON = {}));
  60490. //# sourceMappingURL=babylon.videoTexture.js.map
  60491. "use strict";
  60492. var BABYLON;
  60493. (function (BABYLON) {
  60494. var RawTexture = /** @class */ (function (_super) {
  60495. __extends(RawTexture, _super);
  60496. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60497. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60498. if (invertY === void 0) { invertY = false; }
  60499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60500. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60501. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60502. _this.format = format;
  60503. _this._engine = scene.getEngine();
  60504. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60505. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60506. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60507. return _this;
  60508. }
  60509. RawTexture.prototype.update = function (data) {
  60510. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60511. };
  60512. // Statics
  60513. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60514. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60515. if (invertY === void 0) { invertY = false; }
  60516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60517. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60518. };
  60519. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60520. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60521. if (invertY === void 0) { invertY = false; }
  60522. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60523. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60524. };
  60525. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60526. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60527. if (invertY === void 0) { invertY = false; }
  60528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60529. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60530. };
  60531. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60532. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60533. if (invertY === void 0) { invertY = false; }
  60534. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60535. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60536. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60537. };
  60538. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60539. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60540. if (invertY === void 0) { invertY = false; }
  60541. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60542. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60543. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60544. };
  60545. return RawTexture;
  60546. }(BABYLON.Texture));
  60547. BABYLON.RawTexture = RawTexture;
  60548. })(BABYLON || (BABYLON = {}));
  60549. //# sourceMappingURL=babylon.rawTexture.js.map
  60550. "use strict";
  60551. var BABYLON;
  60552. (function (BABYLON) {
  60553. /**
  60554. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60555. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60556. */
  60557. var PostProcess = /** @class */ (function () {
  60558. /**
  60559. * Creates a new instance PostProcess
  60560. * @param name The name of the PostProcess.
  60561. * @param fragmentUrl The url of the fragment shader to be used.
  60562. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60563. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60564. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60565. * @param camera The camera to apply the render pass to.
  60566. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60567. * @param engine The engine which the post process will be applied. (default: current engine)
  60568. * @param reusable If the post process can be reused on the same frame. (default: false)
  60569. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60570. * @param textureType Type of textures used when performing the post process. (default: 0)
  60571. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60572. * @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
  60573. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60574. */
  60575. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60577. if (defines === void 0) { defines = null; }
  60578. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60579. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60580. if (blockCompilation === void 0) { blockCompilation = false; }
  60581. this.name = name;
  60582. /**
  60583. * Width of the texture to apply the post process on
  60584. */
  60585. this.width = -1;
  60586. /**
  60587. * Height of the texture to apply the post process on
  60588. */
  60589. this.height = -1;
  60590. /**
  60591. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60592. */
  60593. this._outputTexture = null;
  60594. /**
  60595. * If the buffer needs to be cleared before applying the post process. (default: true)
  60596. * Should be set to false if shader will overwrite all previous pixels.
  60597. */
  60598. this.autoClear = true;
  60599. /**
  60600. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60601. */
  60602. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60603. /**
  60604. * Animations to be used for the post processing
  60605. */
  60606. this.animations = new Array();
  60607. /**
  60608. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60609. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60610. */
  60611. this.enablePixelPerfectMode = false;
  60612. /**
  60613. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60614. */
  60615. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60616. /**
  60617. * Force textures to be a power of two (default: false)
  60618. */
  60619. this.alwaysForcePOT = false;
  60620. /**
  60621. * Number of sample textures (default: 1)
  60622. */
  60623. this.samples = 1;
  60624. /**
  60625. * Modify the scale of the post process to be the same as the viewport (default: false)
  60626. */
  60627. this.adaptScaleToCurrentViewport = false;
  60628. this._reusable = false;
  60629. /**
  60630. * Smart array of input and output textures for the post process.
  60631. */
  60632. this._textures = new BABYLON.SmartArray(2);
  60633. /**
  60634. * The index in _textures that corresponds to the output texture.
  60635. */
  60636. this._currentRenderTextureInd = 0;
  60637. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60638. this._texelSize = BABYLON.Vector2.Zero();
  60639. // Events
  60640. /**
  60641. * An event triggered when the postprocess is activated.
  60642. * @type {BABYLON.Observable}
  60643. */
  60644. this.onActivateObservable = new BABYLON.Observable();
  60645. /**
  60646. * An event triggered when the postprocess changes its size.
  60647. * @type {BABYLON.Observable}
  60648. */
  60649. this.onSizeChangedObservable = new BABYLON.Observable();
  60650. /**
  60651. * An event triggered when the postprocess applies its effect.
  60652. * @type {BABYLON.Observable}
  60653. */
  60654. this.onApplyObservable = new BABYLON.Observable();
  60655. /**
  60656. * An event triggered before rendering the postprocess
  60657. * @type {BABYLON.Observable}
  60658. */
  60659. this.onBeforeRenderObservable = new BABYLON.Observable();
  60660. /**
  60661. * An event triggered after rendering the postprocess
  60662. * @type {BABYLON.Observable}
  60663. */
  60664. this.onAfterRenderObservable = new BABYLON.Observable();
  60665. if (camera != null) {
  60666. this._camera = camera;
  60667. this._scene = camera.getScene();
  60668. camera.attachPostProcess(this);
  60669. this._engine = this._scene.getEngine();
  60670. this._scene.postProcesses.push(this);
  60671. }
  60672. else if (engine) {
  60673. this._engine = engine;
  60674. this._engine.postProcesses.push(this);
  60675. }
  60676. this._options = options;
  60677. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60678. this._reusable = reusable || false;
  60679. this._textureType = textureType;
  60680. this._samplers = samplers || [];
  60681. this._samplers.push("textureSampler");
  60682. this._fragmentUrl = fragmentUrl;
  60683. this._vertexUrl = vertexUrl;
  60684. this._parameters = parameters || [];
  60685. this._parameters.push("scale");
  60686. this._indexParameters = indexParameters;
  60687. if (!blockCompilation) {
  60688. this.updateEffect(defines);
  60689. }
  60690. }
  60691. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60692. /**
  60693. * A function that is added to the onActivateObservable
  60694. */
  60695. set: function (callback) {
  60696. if (this._onActivateObserver) {
  60697. this.onActivateObservable.remove(this._onActivateObserver);
  60698. }
  60699. if (callback) {
  60700. this._onActivateObserver = this.onActivateObservable.add(callback);
  60701. }
  60702. },
  60703. enumerable: true,
  60704. configurable: true
  60705. });
  60706. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60707. /**
  60708. * A function that is added to the onSizeChangedObservable
  60709. */
  60710. set: function (callback) {
  60711. if (this._onSizeChangedObserver) {
  60712. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60713. }
  60714. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60715. },
  60716. enumerable: true,
  60717. configurable: true
  60718. });
  60719. Object.defineProperty(PostProcess.prototype, "onApply", {
  60720. /**
  60721. * A function that is added to the onApplyObservable
  60722. */
  60723. set: function (callback) {
  60724. if (this._onApplyObserver) {
  60725. this.onApplyObservable.remove(this._onApplyObserver);
  60726. }
  60727. this._onApplyObserver = this.onApplyObservable.add(callback);
  60728. },
  60729. enumerable: true,
  60730. configurable: true
  60731. });
  60732. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60733. /**
  60734. * A function that is added to the onBeforeRenderObservable
  60735. */
  60736. set: function (callback) {
  60737. if (this._onBeforeRenderObserver) {
  60738. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60739. }
  60740. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60741. },
  60742. enumerable: true,
  60743. configurable: true
  60744. });
  60745. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60746. /**
  60747. * A function that is added to the onAfterRenderObservable
  60748. */
  60749. set: function (callback) {
  60750. if (this._onAfterRenderObserver) {
  60751. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60752. }
  60753. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60754. },
  60755. enumerable: true,
  60756. configurable: true
  60757. });
  60758. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60759. /**
  60760. * 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
  60761. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60762. */
  60763. get: function () {
  60764. return this._textures.data[this._currentRenderTextureInd];
  60765. },
  60766. set: function (value) {
  60767. this._forcedOutputTexture = value;
  60768. },
  60769. enumerable: true,
  60770. configurable: true
  60771. });
  60772. /**
  60773. * Gets the camera which post process is applied to.
  60774. * @returns The camera the post process is applied to.
  60775. */
  60776. PostProcess.prototype.getCamera = function () {
  60777. return this._camera;
  60778. };
  60779. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60780. /**
  60781. * Gets the texel size of the postprocess.
  60782. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60783. */
  60784. get: function () {
  60785. if (this._shareOutputWithPostProcess) {
  60786. return this._shareOutputWithPostProcess.texelSize;
  60787. }
  60788. if (this._forcedOutputTexture) {
  60789. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60790. }
  60791. return this._texelSize;
  60792. },
  60793. enumerable: true,
  60794. configurable: true
  60795. });
  60796. /**
  60797. * Gets the engine which this post process belongs to.
  60798. * @returns The engine the post process was enabled with.
  60799. */
  60800. PostProcess.prototype.getEngine = function () {
  60801. return this._engine;
  60802. };
  60803. /**
  60804. * The effect that is created when initializing the post process.
  60805. * @returns The created effect corrisponding the the postprocess.
  60806. */
  60807. PostProcess.prototype.getEffect = function () {
  60808. return this._effect;
  60809. };
  60810. /**
  60811. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60812. * @param postProcess The post process to share the output with.
  60813. * @returns This post process.
  60814. */
  60815. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60816. this._disposeTextures();
  60817. this._shareOutputWithPostProcess = postProcess;
  60818. return this;
  60819. };
  60820. /**
  60821. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60822. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60823. */
  60824. PostProcess.prototype.useOwnOutput = function () {
  60825. if (this._textures.length == 0) {
  60826. this._textures = new BABYLON.SmartArray(2);
  60827. }
  60828. this._shareOutputWithPostProcess = null;
  60829. };
  60830. /**
  60831. * Updates the effect with the current post process compile time values and recompiles the shader.
  60832. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60833. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60834. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60835. * @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
  60836. * @param onCompiled Called when the shader has been compiled.
  60837. * @param onError Called if there is an error when compiling a shader.
  60838. */
  60839. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60840. if (defines === void 0) { defines = null; }
  60841. if (uniforms === void 0) { uniforms = null; }
  60842. if (samplers === void 0) { samplers = null; }
  60843. 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);
  60844. };
  60845. /**
  60846. * The post process is reusable if it can be used multiple times within one frame.
  60847. * @returns If the post process is reusable
  60848. */
  60849. PostProcess.prototype.isReusable = function () {
  60850. return this._reusable;
  60851. };
  60852. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60853. PostProcess.prototype.markTextureDirty = function () {
  60854. this.width = -1;
  60855. };
  60856. /**
  60857. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60858. * 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.
  60859. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60860. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60861. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60862. * @returns The target texture that was bound to be written to.
  60863. */
  60864. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60865. var _this = this;
  60866. if (sourceTexture === void 0) { sourceTexture = null; }
  60867. camera = camera || this._camera;
  60868. var scene = camera.getScene();
  60869. var engine = scene.getEngine();
  60870. var maxSize = engine.getCaps().maxTextureSize;
  60871. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60872. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60873. // 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
  60874. var webVRCamera = camera.parent;
  60875. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60876. requiredWidth /= 2;
  60877. }
  60878. var desiredWidth = (this._options.width || requiredWidth);
  60879. var desiredHeight = this._options.height || requiredHeight;
  60880. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60881. if (this.adaptScaleToCurrentViewport) {
  60882. var currentViewport = engine.currentViewport;
  60883. if (currentViewport) {
  60884. desiredWidth *= currentViewport.width;
  60885. desiredHeight *= currentViewport.height;
  60886. }
  60887. }
  60888. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60889. if (!this._options.width) {
  60890. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60891. }
  60892. if (!this._options.height) {
  60893. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60894. }
  60895. }
  60896. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60897. if (this._textures.length > 0) {
  60898. for (var i = 0; i < this._textures.length; i++) {
  60899. this._engine._releaseTexture(this._textures.data[i]);
  60900. }
  60901. this._textures.reset();
  60902. }
  60903. this.width = desiredWidth;
  60904. this.height = desiredHeight;
  60905. var textureSize = { width: this.width, height: this.height };
  60906. var textureOptions = {
  60907. generateMipMaps: false,
  60908. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60909. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60910. samplingMode: this.renderTargetSamplingMode,
  60911. type: this._textureType
  60912. };
  60913. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60914. if (this._reusable) {
  60915. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60916. }
  60917. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60918. this.onSizeChangedObservable.notifyObservers(this);
  60919. }
  60920. this._textures.forEach(function (texture) {
  60921. if (texture.samples !== _this.samples) {
  60922. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60923. }
  60924. });
  60925. }
  60926. var target;
  60927. if (this._shareOutputWithPostProcess) {
  60928. target = this._shareOutputWithPostProcess.inputTexture;
  60929. }
  60930. else if (this._forcedOutputTexture) {
  60931. target = this._forcedOutputTexture;
  60932. this.width = this._forcedOutputTexture.width;
  60933. this.height = this._forcedOutputTexture.height;
  60934. }
  60935. else {
  60936. target = this.inputTexture;
  60937. }
  60938. // Bind the input of this post process to be used as the output of the previous post process.
  60939. if (this.enablePixelPerfectMode) {
  60940. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60941. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60942. }
  60943. else {
  60944. this._scaleRatio.copyFromFloats(1, 1);
  60945. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60946. }
  60947. this.onActivateObservable.notifyObservers(camera);
  60948. // Clear
  60949. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60950. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60951. }
  60952. if (this._reusable) {
  60953. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60954. }
  60955. return target;
  60956. };
  60957. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60958. /**
  60959. * If the post process is supported.
  60960. */
  60961. get: function () {
  60962. return this._effect.isSupported;
  60963. },
  60964. enumerable: true,
  60965. configurable: true
  60966. });
  60967. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60968. /**
  60969. * The aspect ratio of the output texture.
  60970. */
  60971. get: function () {
  60972. if (this._shareOutputWithPostProcess) {
  60973. return this._shareOutputWithPostProcess.aspectRatio;
  60974. }
  60975. if (this._forcedOutputTexture) {
  60976. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60977. }
  60978. return this.width / this.height;
  60979. },
  60980. enumerable: true,
  60981. configurable: true
  60982. });
  60983. /**
  60984. * Get a value indicating if the post-process is ready to be used
  60985. * @returns true if the post-process is ready (shader is compiled)
  60986. */
  60987. PostProcess.prototype.isReady = function () {
  60988. return this._effect && this._effect.isReady();
  60989. };
  60990. /**
  60991. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60992. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60993. */
  60994. PostProcess.prototype.apply = function () {
  60995. // Check
  60996. if (!this._effect || !this._effect.isReady())
  60997. return null;
  60998. // States
  60999. this._engine.enableEffect(this._effect);
  61000. this._engine.setState(false);
  61001. this._engine.setDepthBuffer(false);
  61002. this._engine.setDepthWrite(false);
  61003. // Alpha
  61004. this._engine.setAlphaMode(this.alphaMode);
  61005. if (this.alphaConstants) {
  61006. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  61007. }
  61008. // Bind the output texture of the preivous post process as the input to this post process.
  61009. var source;
  61010. if (this._shareOutputWithPostProcess) {
  61011. source = this._shareOutputWithPostProcess.inputTexture;
  61012. }
  61013. else if (this._forcedOutputTexture) {
  61014. source = this._forcedOutputTexture;
  61015. }
  61016. else {
  61017. source = this.inputTexture;
  61018. }
  61019. this._effect._bindTexture("textureSampler", source);
  61020. // Parameters
  61021. this._effect.setVector2("scale", this._scaleRatio);
  61022. this.onApplyObservable.notifyObservers(this._effect);
  61023. return this._effect;
  61024. };
  61025. PostProcess.prototype._disposeTextures = function () {
  61026. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  61027. return;
  61028. }
  61029. if (this._textures.length > 0) {
  61030. for (var i = 0; i < this._textures.length; i++) {
  61031. this._engine._releaseTexture(this._textures.data[i]);
  61032. }
  61033. }
  61034. this._textures.dispose();
  61035. };
  61036. /**
  61037. * Disposes the post process.
  61038. * @param camera The camera to dispose the post process on.
  61039. */
  61040. PostProcess.prototype.dispose = function (camera) {
  61041. camera = camera || this._camera;
  61042. this._disposeTextures();
  61043. if (this._scene) {
  61044. var index_1 = this._scene.postProcesses.indexOf(this);
  61045. if (index_1 !== -1) {
  61046. this._scene.postProcesses.splice(index_1, 1);
  61047. }
  61048. }
  61049. else {
  61050. var index_2 = this._engine.postProcesses.indexOf(this);
  61051. if (index_2 !== -1) {
  61052. this._engine.postProcesses.splice(index_2, 1);
  61053. }
  61054. }
  61055. if (!camera) {
  61056. return;
  61057. }
  61058. camera.detachPostProcess(this);
  61059. var index = camera._postProcesses.indexOf(this);
  61060. if (index === 0 && camera._postProcesses.length > 0) {
  61061. var firstPostProcess = this._camera._getFirstPostProcess();
  61062. if (firstPostProcess) {
  61063. firstPostProcess.markTextureDirty();
  61064. }
  61065. }
  61066. this.onActivateObservable.clear();
  61067. this.onAfterRenderObservable.clear();
  61068. this.onApplyObservable.clear();
  61069. this.onBeforeRenderObservable.clear();
  61070. this.onSizeChangedObservable.clear();
  61071. };
  61072. return PostProcess;
  61073. }());
  61074. BABYLON.PostProcess = PostProcess;
  61075. })(BABYLON || (BABYLON = {}));
  61076. //# sourceMappingURL=babylon.postProcess.js.map
  61077. "use strict";
  61078. var BABYLON;
  61079. (function (BABYLON) {
  61080. var PassPostProcess = /** @class */ (function (_super) {
  61081. __extends(PassPostProcess, _super);
  61082. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  61083. if (camera === void 0) { camera = null; }
  61084. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61085. if (blockCompilation === void 0) { blockCompilation = false; }
  61086. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  61087. }
  61088. return PassPostProcess;
  61089. }(BABYLON.PostProcess));
  61090. BABYLON.PassPostProcess = PassPostProcess;
  61091. })(BABYLON || (BABYLON = {}));
  61092. //# sourceMappingURL=babylon.passPostProcess.js.map
  61093. "use strict";
  61094. var __assign = (this && this.__assign) || Object.assign || function(t) {
  61095. for (var s, i = 1, n = arguments.length; i < n; i++) {
  61096. s = arguments[i];
  61097. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  61098. t[p] = s[p];
  61099. }
  61100. return t;
  61101. };
  61102. var BABYLON;
  61103. (function (BABYLON) {
  61104. /**
  61105. * Default implementation IShadowGenerator.
  61106. * This is the main object responsible of generating shadows in the framework.
  61107. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  61108. */
  61109. var ShadowGenerator = /** @class */ (function () {
  61110. /**
  61111. * Creates a ShadowGenerator object.
  61112. * A ShadowGenerator is the required tool to use the shadows.
  61113. * Each light casting shadows needs to use its own ShadowGenerator.
  61114. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  61115. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  61116. * @param light The light object generating the shadows.
  61117. * @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.
  61118. */
  61119. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  61120. this._bias = 0.00005;
  61121. this._normalBias = 0;
  61122. this._blurBoxOffset = 1;
  61123. this._blurScale = 2;
  61124. this._blurKernel = 1;
  61125. this._useKernelBlur = false;
  61126. this._filter = ShadowGenerator.FILTER_NONE;
  61127. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  61128. this._contactHardeningLightSizeUVRatio = 0.1;
  61129. this._darkness = 0;
  61130. this._transparencyShadow = false;
  61131. /**
  61132. * Controls the extent to which the shadows fade out at the edge of the frustum
  61133. * Used only by directionals and spots
  61134. */
  61135. this.frustumEdgeFalloff = 0;
  61136. /**
  61137. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  61138. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  61139. * It might on the other hand introduce peter panning.
  61140. */
  61141. this.forceBackFacesOnly = false;
  61142. this._lightDirection = BABYLON.Vector3.Zero();
  61143. this._viewMatrix = BABYLON.Matrix.Zero();
  61144. this._projectionMatrix = BABYLON.Matrix.Zero();
  61145. this._transformMatrix = BABYLON.Matrix.Zero();
  61146. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61147. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  61148. this._currentFaceIndex = 0;
  61149. this._currentFaceIndexCache = 0;
  61150. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  61151. this._mapSize = mapSize;
  61152. this._light = light;
  61153. this._scene = light.getScene();
  61154. light._shadowGenerator = this;
  61155. // Texture type fallback from float to int if not supported.
  61156. var caps = this._scene.getEngine().getCaps();
  61157. if (!useFullFloatFirst) {
  61158. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61159. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61160. }
  61161. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61162. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61163. }
  61164. else {
  61165. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61166. }
  61167. }
  61168. else {
  61169. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  61170. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61171. }
  61172. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  61173. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61174. }
  61175. else {
  61176. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61177. }
  61178. }
  61179. this._initializeGenerator();
  61180. this._applyFilterValues();
  61181. }
  61182. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  61183. /**
  61184. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  61185. */
  61186. get: function () {
  61187. return this._bias;
  61188. },
  61189. /**
  61190. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  61191. */
  61192. set: function (bias) {
  61193. this._bias = bias;
  61194. },
  61195. enumerable: true,
  61196. configurable: true
  61197. });
  61198. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  61199. /**
  61200. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61201. */
  61202. get: function () {
  61203. return this._normalBias;
  61204. },
  61205. /**
  61206. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  61207. */
  61208. set: function (normalBias) {
  61209. this._normalBias = normalBias;
  61210. },
  61211. enumerable: true,
  61212. configurable: true
  61213. });
  61214. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  61215. /**
  61216. * Gets the blur box offset: offset applied during the blur pass.
  61217. * Only usefull if useKernelBlur = false
  61218. */
  61219. get: function () {
  61220. return this._blurBoxOffset;
  61221. },
  61222. /**
  61223. * Sets the blur box offset: offset applied during the blur pass.
  61224. * Only usefull if useKernelBlur = false
  61225. */
  61226. set: function (value) {
  61227. if (this._blurBoxOffset === value) {
  61228. return;
  61229. }
  61230. this._blurBoxOffset = value;
  61231. this._disposeBlurPostProcesses();
  61232. },
  61233. enumerable: true,
  61234. configurable: true
  61235. });
  61236. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  61237. /**
  61238. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  61239. * 2 means half of the size.
  61240. */
  61241. get: function () {
  61242. return this._blurScale;
  61243. },
  61244. /**
  61245. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  61246. * 2 means half of the size.
  61247. */
  61248. set: function (value) {
  61249. if (this._blurScale === value) {
  61250. return;
  61251. }
  61252. this._blurScale = value;
  61253. this._disposeBlurPostProcesses();
  61254. },
  61255. enumerable: true,
  61256. configurable: true
  61257. });
  61258. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  61259. /**
  61260. * Gets the blur kernel: kernel size of the blur pass.
  61261. * Only usefull if useKernelBlur = true
  61262. */
  61263. get: function () {
  61264. return this._blurKernel;
  61265. },
  61266. /**
  61267. * Sets the blur kernel: kernel size of the blur pass.
  61268. * Only usefull if useKernelBlur = true
  61269. */
  61270. set: function (value) {
  61271. if (this._blurKernel === value) {
  61272. return;
  61273. }
  61274. this._blurKernel = value;
  61275. this._disposeBlurPostProcesses();
  61276. },
  61277. enumerable: true,
  61278. configurable: true
  61279. });
  61280. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  61281. /**
  61282. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  61283. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61284. */
  61285. get: function () {
  61286. return this._useKernelBlur;
  61287. },
  61288. /**
  61289. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61290. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61291. */
  61292. set: function (value) {
  61293. if (this._useKernelBlur === value) {
  61294. return;
  61295. }
  61296. this._useKernelBlur = value;
  61297. this._disposeBlurPostProcesses();
  61298. },
  61299. enumerable: true,
  61300. configurable: true
  61301. });
  61302. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61303. /**
  61304. * Gets the depth scale used in ESM mode.
  61305. */
  61306. get: function () {
  61307. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61308. },
  61309. /**
  61310. * Sets the depth scale used in ESM mode.
  61311. * This can override the scale stored on the light.
  61312. */
  61313. set: function (value) {
  61314. this._depthScale = value;
  61315. },
  61316. enumerable: true,
  61317. configurable: true
  61318. });
  61319. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61320. /**
  61321. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61322. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61323. */
  61324. get: function () {
  61325. return this._filter;
  61326. },
  61327. /**
  61328. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61329. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61330. */
  61331. set: function (value) {
  61332. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61333. if (this._light.needCube()) {
  61334. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61335. this.useExponentialShadowMap = true;
  61336. return;
  61337. }
  61338. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61339. this.useCloseExponentialShadowMap = true;
  61340. return;
  61341. }
  61342. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61343. this.usePoissonSampling = true;
  61344. return;
  61345. }
  61346. }
  61347. // Weblg1 fallback for PCF.
  61348. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61349. if (this._scene.getEngine().webGLVersion === 1) {
  61350. this.usePoissonSampling = true;
  61351. return;
  61352. }
  61353. }
  61354. if (this._filter === value) {
  61355. return;
  61356. }
  61357. this._filter = value;
  61358. this._disposeBlurPostProcesses();
  61359. this._applyFilterValues();
  61360. this._light._markMeshesAsLightDirty();
  61361. },
  61362. enumerable: true,
  61363. configurable: true
  61364. });
  61365. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61366. /**
  61367. * Gets if the current filter is set to Poisson Sampling.
  61368. */
  61369. get: function () {
  61370. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61371. },
  61372. /**
  61373. * Sets the current filter to Poisson Sampling.
  61374. */
  61375. set: function (value) {
  61376. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61377. return;
  61378. }
  61379. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61380. },
  61381. enumerable: true,
  61382. configurable: true
  61383. });
  61384. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61385. /**
  61386. * Gets if the current filter is set to VSM.
  61387. * DEPRECATED. Should use useExponentialShadowMap instead.
  61388. */
  61389. get: function () {
  61390. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61391. return this.useExponentialShadowMap;
  61392. },
  61393. /**
  61394. * Sets the current filter is to VSM.
  61395. * DEPRECATED. Should use useExponentialShadowMap instead.
  61396. */
  61397. set: function (value) {
  61398. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61399. this.useExponentialShadowMap = value;
  61400. },
  61401. enumerable: true,
  61402. configurable: true
  61403. });
  61404. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61405. /**
  61406. * Gets if the current filter is set to blurred VSM.
  61407. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61408. */
  61409. get: function () {
  61410. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61411. return this.useBlurExponentialShadowMap;
  61412. },
  61413. /**
  61414. * Sets the current filter is to blurred VSM.
  61415. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61416. */
  61417. set: function (value) {
  61418. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61419. this.useBlurExponentialShadowMap = value;
  61420. },
  61421. enumerable: true,
  61422. configurable: true
  61423. });
  61424. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61425. /**
  61426. * Gets if the current filter is set to ESM.
  61427. */
  61428. get: function () {
  61429. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61430. },
  61431. /**
  61432. * Sets the current filter is to ESM.
  61433. */
  61434. set: function (value) {
  61435. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61436. return;
  61437. }
  61438. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61439. },
  61440. enumerable: true,
  61441. configurable: true
  61442. });
  61443. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61444. /**
  61445. * Gets if the current filter is set to filtered ESM.
  61446. */
  61447. get: function () {
  61448. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61449. },
  61450. /**
  61451. * Gets if the current filter is set to filtered ESM.
  61452. */
  61453. set: function (value) {
  61454. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61455. return;
  61456. }
  61457. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61458. },
  61459. enumerable: true,
  61460. configurable: true
  61461. });
  61462. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61463. /**
  61464. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61465. * exponential to prevent steep falloff artifacts).
  61466. */
  61467. get: function () {
  61468. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61469. },
  61470. /**
  61471. * Sets the current filter to "close ESM" (using the inverse of the
  61472. * exponential to prevent steep falloff artifacts).
  61473. */
  61474. set: function (value) {
  61475. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61476. return;
  61477. }
  61478. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61479. },
  61480. enumerable: true,
  61481. configurable: true
  61482. });
  61483. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61484. /**
  61485. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61486. * exponential to prevent steep falloff artifacts).
  61487. */
  61488. get: function () {
  61489. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61490. },
  61491. /**
  61492. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61493. * exponential to prevent steep falloff artifacts).
  61494. */
  61495. set: function (value) {
  61496. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61497. return;
  61498. }
  61499. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61500. },
  61501. enumerable: true,
  61502. configurable: true
  61503. });
  61504. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61505. /**
  61506. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61507. */
  61508. get: function () {
  61509. return this.filter === ShadowGenerator.FILTER_PCF;
  61510. },
  61511. /**
  61512. * Sets the current filter to "PCF" (percentage closer filtering).
  61513. */
  61514. set: function (value) {
  61515. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61516. return;
  61517. }
  61518. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61519. },
  61520. enumerable: true,
  61521. configurable: true
  61522. });
  61523. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61524. /**
  61525. * Gets the PCF or PCSS Quality.
  61526. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61527. */
  61528. get: function () {
  61529. return this._filteringQuality;
  61530. },
  61531. /**
  61532. * Sets the PCF or PCSS Quality.
  61533. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61534. */
  61535. set: function (filteringQuality) {
  61536. this._filteringQuality = filteringQuality;
  61537. },
  61538. enumerable: true,
  61539. configurable: true
  61540. });
  61541. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61542. /**
  61543. * Gets if the current filter is set to "PCSS" (contact hardening).
  61544. */
  61545. get: function () {
  61546. return this.filter === ShadowGenerator.FILTER_PCSS;
  61547. },
  61548. /**
  61549. * Sets the current filter to "PCSS" (contact hardening).
  61550. */
  61551. set: function (value) {
  61552. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61553. return;
  61554. }
  61555. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61556. },
  61557. enumerable: true,
  61558. configurable: true
  61559. });
  61560. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61561. /**
  61562. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61563. * Using a ratio helps keeping shape stability independently of the map size.
  61564. *
  61565. * It does not account for the light projection as it was having too much
  61566. * instability during the light setup or during light position changes.
  61567. *
  61568. * Only valid if useContactHardeningShadow is true.
  61569. */
  61570. get: function () {
  61571. return this._contactHardeningLightSizeUVRatio;
  61572. },
  61573. /**
  61574. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61575. * Using a ratio helps keeping shape stability independently of the map size.
  61576. *
  61577. * It does not account for the light projection as it was having too much
  61578. * instability during the light setup or during light position changes.
  61579. *
  61580. * Only valid if useContactHardeningShadow is true.
  61581. */
  61582. set: function (contactHardeningLightSizeUVRatio) {
  61583. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61584. },
  61585. enumerable: true,
  61586. configurable: true
  61587. });
  61588. /**
  61589. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61590. * 0 means strongest and 1 would means no shadow.
  61591. * @returns the darkness.
  61592. */
  61593. ShadowGenerator.prototype.getDarkness = function () {
  61594. return this._darkness;
  61595. };
  61596. /**
  61597. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61598. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61599. * @returns the shadow generator allowing fluent coding.
  61600. */
  61601. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61602. if (darkness >= 1.0)
  61603. this._darkness = 1.0;
  61604. else if (darkness <= 0.0)
  61605. this._darkness = 0.0;
  61606. else
  61607. this._darkness = darkness;
  61608. return this;
  61609. };
  61610. /**
  61611. * Sets the ability to have transparent shadow (boolean).
  61612. * @param transparent True if transparent else False
  61613. * @returns the shadow generator allowing fluent coding
  61614. */
  61615. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61616. this._transparencyShadow = transparent;
  61617. return this;
  61618. };
  61619. /**
  61620. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61621. * @returns The render target texture if present otherwise, null
  61622. */
  61623. ShadowGenerator.prototype.getShadowMap = function () {
  61624. return this._shadowMap;
  61625. };
  61626. /**
  61627. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61628. * @returns The render target texture if the shadow map is present otherwise, null
  61629. */
  61630. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61631. if (this._shadowMap2) {
  61632. return this._shadowMap2;
  61633. }
  61634. return this._shadowMap;
  61635. };
  61636. /**
  61637. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61638. * @param mesh Mesh to add
  61639. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61640. * @returns the Shadow Generator itself
  61641. */
  61642. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61643. if (includeDescendants === void 0) { includeDescendants = true; }
  61644. if (!this._shadowMap) {
  61645. return this;
  61646. }
  61647. if (!this._shadowMap.renderList) {
  61648. this._shadowMap.renderList = [];
  61649. }
  61650. this._shadowMap.renderList.push(mesh);
  61651. if (includeDescendants) {
  61652. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61653. }
  61654. return this;
  61655. var _a;
  61656. };
  61657. /**
  61658. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61659. * @param mesh Mesh to remove
  61660. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61661. * @returns the Shadow Generator itself
  61662. */
  61663. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61664. if (includeDescendants === void 0) { includeDescendants = true; }
  61665. if (!this._shadowMap || !this._shadowMap.renderList) {
  61666. return this;
  61667. }
  61668. var index = this._shadowMap.renderList.indexOf(mesh);
  61669. if (index !== -1) {
  61670. this._shadowMap.renderList.splice(index, 1);
  61671. }
  61672. if (includeDescendants) {
  61673. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61674. var child = _a[_i];
  61675. this.removeShadowCaster(child);
  61676. }
  61677. }
  61678. return this;
  61679. };
  61680. /**
  61681. * Returns the associated light object.
  61682. * @returns the light generating the shadow
  61683. */
  61684. ShadowGenerator.prototype.getLight = function () {
  61685. return this._light;
  61686. };
  61687. ShadowGenerator.prototype._initializeGenerator = function () {
  61688. this._light._markMeshesAsLightDirty();
  61689. this._initializeShadowMap();
  61690. };
  61691. ShadowGenerator.prototype._initializeShadowMap = function () {
  61692. var _this = this;
  61693. // Render target
  61694. var engine = this._scene.getEngine();
  61695. if (engine.webGLVersion > 1) {
  61696. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61697. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61698. }
  61699. else {
  61700. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61701. }
  61702. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61703. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61704. this._shadowMap.anisotropicFilteringLevel = 1;
  61705. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61706. this._shadowMap.renderParticles = false;
  61707. this._shadowMap.ignoreCameraViewport = true;
  61708. // Record Face Index before render.
  61709. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61710. _this._currentFaceIndex = faceIndex;
  61711. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61712. engine.setColorWrite(false);
  61713. }
  61714. });
  61715. // Custom render function.
  61716. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61717. // Blur if required afer render.
  61718. this._shadowMap.onAfterUnbindObservable.add(function () {
  61719. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61720. engine.setColorWrite(true);
  61721. }
  61722. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61723. return;
  61724. }
  61725. var shadowMap = _this.getShadowMapForRendering();
  61726. if (shadowMap) {
  61727. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61728. }
  61729. });
  61730. // Clear according to the chosen filter.
  61731. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61732. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61733. this._shadowMap.onClearObservable.add(function (engine) {
  61734. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61735. engine.clear(clearOne, false, true, false);
  61736. }
  61737. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61738. engine.clear(clearZero, true, true, false);
  61739. }
  61740. else {
  61741. engine.clear(clearOne, true, true, false);
  61742. }
  61743. });
  61744. };
  61745. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61746. var _this = this;
  61747. var engine = this._scene.getEngine();
  61748. var targetSize = this._mapSize / this.blurScale;
  61749. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61750. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61751. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61752. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61753. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61754. }
  61755. if (this.useKernelBlur) {
  61756. 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);
  61757. this._kernelBlurXPostprocess.width = targetSize;
  61758. this._kernelBlurXPostprocess.height = targetSize;
  61759. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61760. effect.setTexture("textureSampler", _this._shadowMap);
  61761. });
  61762. 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);
  61763. this._kernelBlurXPostprocess.autoClear = false;
  61764. this._kernelBlurYPostprocess.autoClear = false;
  61765. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61766. this._kernelBlurXPostprocess.packedFloat = true;
  61767. this._kernelBlurYPostprocess.packedFloat = true;
  61768. }
  61769. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61770. }
  61771. else {
  61772. 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);
  61773. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61774. effect.setFloat2("screenSize", targetSize, targetSize);
  61775. effect.setTexture("textureSampler", _this._shadowMap);
  61776. });
  61777. this._boxBlurPostprocess.autoClear = false;
  61778. this._blurPostProcesses = [this._boxBlurPostprocess];
  61779. }
  61780. };
  61781. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61782. var index;
  61783. var engine = this._scene.getEngine();
  61784. if (depthOnlySubMeshes.length) {
  61785. engine.setColorWrite(false);
  61786. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61787. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61788. }
  61789. engine.setColorWrite(true);
  61790. }
  61791. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61792. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61793. }
  61794. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61795. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61796. }
  61797. if (this._transparencyShadow) {
  61798. for (index = 0; index < transparentSubMeshes.length; index++) {
  61799. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61800. }
  61801. }
  61802. };
  61803. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61804. var _this = this;
  61805. var mesh = subMesh.getRenderingMesh();
  61806. var scene = this._scene;
  61807. var engine = scene.getEngine();
  61808. var material = subMesh.getMaterial();
  61809. if (!material) {
  61810. return;
  61811. }
  61812. // Culling
  61813. engine.setState(material.backFaceCulling);
  61814. // Managing instances
  61815. var batch = mesh._getInstancesRenderList(subMesh._id);
  61816. if (batch.mustReturn) {
  61817. return;
  61818. }
  61819. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61820. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61821. engine.enableEffect(this._effect);
  61822. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61823. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61824. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61825. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61826. this._effect.setVector3("lightData", this._cachedDirection);
  61827. }
  61828. else {
  61829. this._effect.setVector3("lightData", this._cachedPosition);
  61830. }
  61831. if (scene.activeCamera) {
  61832. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61833. }
  61834. // Alpha test
  61835. if (material && material.needAlphaTesting()) {
  61836. var alphaTexture = material.getAlphaTestTexture();
  61837. if (alphaTexture) {
  61838. this._effect.setTexture("diffuseSampler", alphaTexture);
  61839. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61840. }
  61841. }
  61842. // Bones
  61843. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61844. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61845. }
  61846. // Morph targets
  61847. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  61848. if (this.forceBackFacesOnly) {
  61849. engine.setState(true, 0, false, true);
  61850. }
  61851. // Draw
  61852. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61853. if (this.forceBackFacesOnly) {
  61854. engine.setState(true, 0, false, false);
  61855. }
  61856. }
  61857. else {
  61858. // Need to reset refresh rate of the shadowMap
  61859. if (this._shadowMap) {
  61860. this._shadowMap.resetRefreshCounter();
  61861. }
  61862. }
  61863. };
  61864. ShadowGenerator.prototype._applyFilterValues = function () {
  61865. if (!this._shadowMap) {
  61866. return;
  61867. }
  61868. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61869. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61870. }
  61871. else {
  61872. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61873. }
  61874. };
  61875. /**
  61876. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61877. * @param onCompiled Callback triggered at the and of the effects compilation
  61878. * @param options Sets of optional options forcing the compilation with different modes
  61879. */
  61880. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61881. var _this = this;
  61882. var localOptions = __assign({ useInstances: false }, options);
  61883. var shadowMap = this.getShadowMap();
  61884. if (!shadowMap) {
  61885. if (onCompiled) {
  61886. onCompiled(this);
  61887. }
  61888. return;
  61889. }
  61890. var renderList = shadowMap.renderList;
  61891. if (!renderList) {
  61892. if (onCompiled) {
  61893. onCompiled(this);
  61894. }
  61895. return;
  61896. }
  61897. var subMeshes = new Array();
  61898. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61899. var mesh = renderList_1[_i];
  61900. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61901. }
  61902. if (subMeshes.length === 0) {
  61903. if (onCompiled) {
  61904. onCompiled(this);
  61905. }
  61906. return;
  61907. }
  61908. var currentIndex = 0;
  61909. var checkReady = function () {
  61910. if (!_this._scene || !_this._scene.getEngine()) {
  61911. return;
  61912. }
  61913. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61914. currentIndex++;
  61915. if (currentIndex >= subMeshes.length) {
  61916. if (onCompiled) {
  61917. onCompiled(_this);
  61918. }
  61919. return;
  61920. }
  61921. }
  61922. setTimeout(checkReady, 16);
  61923. };
  61924. checkReady();
  61925. };
  61926. /**
  61927. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61928. * @param options Sets of optional options forcing the compilation with different modes
  61929. * @returns A promise that resolves when the compilation completes
  61930. */
  61931. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61932. var _this = this;
  61933. return new Promise(function (resolve) {
  61934. _this.forceCompilation(function () {
  61935. resolve();
  61936. }, options);
  61937. });
  61938. };
  61939. /**
  61940. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61941. * @param subMesh The submesh we want to render in the shadow map
  61942. * @param useInstances Defines wether will draw in the map using instances
  61943. * @returns true if ready otherwise, false
  61944. */
  61945. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61946. var defines = [];
  61947. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61948. defines.push("#define FLOAT");
  61949. }
  61950. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61951. defines.push("#define ESM");
  61952. }
  61953. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61954. defines.push("#define DEPTHTEXTURE");
  61955. }
  61956. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61957. var mesh = subMesh.getMesh();
  61958. var material = subMesh.getMaterial();
  61959. // Normal bias.
  61960. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61961. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61962. defines.push("#define NORMAL");
  61963. if (mesh.nonUniformScaling) {
  61964. defines.push("#define NONUNIFORMSCALING");
  61965. }
  61966. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61967. defines.push("#define DIRECTIONINLIGHTDATA");
  61968. }
  61969. }
  61970. // Alpha test
  61971. if (material && material.needAlphaTesting()) {
  61972. var alphaTexture = material.getAlphaTestTexture();
  61973. if (alphaTexture) {
  61974. defines.push("#define ALPHATEST");
  61975. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61976. attribs.push(BABYLON.VertexBuffer.UVKind);
  61977. defines.push("#define UV1");
  61978. }
  61979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61980. if (alphaTexture.coordinatesIndex === 1) {
  61981. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61982. defines.push("#define UV2");
  61983. }
  61984. }
  61985. }
  61986. }
  61987. // Bones
  61988. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61989. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61990. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61991. if (mesh.numBoneInfluencers > 4) {
  61992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61994. }
  61995. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61996. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61997. }
  61998. else {
  61999. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62000. }
  62001. // Morph targets
  62002. var manager = mesh.morphTargetManager;
  62003. var morphInfluencers = 0;
  62004. if (manager) {
  62005. if (manager.numInfluencers > 0) {
  62006. defines.push("#define MORPHTARGETS");
  62007. morphInfluencers = manager.numInfluencers;
  62008. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  62009. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  62010. }
  62011. }
  62012. // Instances
  62013. if (useInstances) {
  62014. defines.push("#define INSTANCES");
  62015. attribs.push("world0");
  62016. attribs.push("world1");
  62017. attribs.push("world2");
  62018. attribs.push("world3");
  62019. }
  62020. // Get correct effect
  62021. var join = defines.join("\n");
  62022. if (this._cachedDefines !== join) {
  62023. this._cachedDefines = join;
  62024. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  62025. }
  62026. if (!this._effect.isReady()) {
  62027. return false;
  62028. }
  62029. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62030. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  62031. this._initializeBlurRTTAndPostProcesses();
  62032. }
  62033. }
  62034. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  62035. return false;
  62036. }
  62037. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  62038. return false;
  62039. }
  62040. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  62041. return false;
  62042. }
  62043. return true;
  62044. };
  62045. /**
  62046. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  62047. * @param defines Defines of the material we want to update
  62048. * @param lightIndex Index of the light in the enabled light list of the material
  62049. */
  62050. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  62051. var scene = this._scene;
  62052. var light = this._light;
  62053. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62054. return;
  62055. }
  62056. defines["SHADOW" + lightIndex] = true;
  62057. if (this.useContactHardeningShadow) {
  62058. defines["SHADOWPCSS" + lightIndex] = true;
  62059. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62060. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62061. }
  62062. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62063. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62064. }
  62065. // else default to high.
  62066. }
  62067. if (this.usePercentageCloserFiltering) {
  62068. defines["SHADOWPCF" + lightIndex] = true;
  62069. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  62070. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  62071. }
  62072. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  62073. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  62074. }
  62075. // else default to high.
  62076. }
  62077. else if (this.usePoissonSampling) {
  62078. defines["SHADOWPOISSON" + lightIndex] = true;
  62079. }
  62080. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  62081. defines["SHADOWESM" + lightIndex] = true;
  62082. }
  62083. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  62084. defines["SHADOWCLOSEESM" + lightIndex] = true;
  62085. }
  62086. if (light.needCube()) {
  62087. defines["SHADOWCUBE" + lightIndex] = true;
  62088. }
  62089. };
  62090. /**
  62091. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  62092. * defined in the generator but impacting the effect).
  62093. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  62094. * @param effect The effect we are binfing the information for
  62095. */
  62096. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  62097. var light = this._light;
  62098. var scene = this._scene;
  62099. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  62100. return;
  62101. }
  62102. var camera = scene.activeCamera;
  62103. if (!camera) {
  62104. return;
  62105. }
  62106. var shadowMap = this.getShadowMap();
  62107. if (!shadowMap) {
  62108. return;
  62109. }
  62110. if (!light.needCube()) {
  62111. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  62112. }
  62113. // Only PCF uses depth stencil texture.
  62114. if (this._filter === ShadowGenerator.FILTER_PCF) {
  62115. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62116. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62117. }
  62118. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  62119. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62120. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  62121. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  62122. }
  62123. else {
  62124. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  62125. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  62126. }
  62127. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  62128. };
  62129. /**
  62130. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  62131. * (eq to shadow prjection matrix * light transform matrix)
  62132. * @returns The transform matrix used to create the shadow map
  62133. */
  62134. ShadowGenerator.prototype.getTransformMatrix = function () {
  62135. var scene = this._scene;
  62136. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  62137. return this._transformMatrix;
  62138. }
  62139. this._currentRenderID = scene.getRenderId();
  62140. this._currentFaceIndexCache = this._currentFaceIndex;
  62141. var lightPosition = this._light.position;
  62142. if (this._light.computeTransformedInformation()) {
  62143. lightPosition = this._light.transformedPosition;
  62144. }
  62145. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  62146. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  62147. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  62148. }
  62149. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  62150. this._cachedPosition.copyFrom(lightPosition);
  62151. this._cachedDirection.copyFrom(this._lightDirection);
  62152. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  62153. var shadowMap = this.getShadowMap();
  62154. if (shadowMap) {
  62155. var renderList = shadowMap.renderList;
  62156. if (renderList) {
  62157. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  62158. }
  62159. }
  62160. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  62161. }
  62162. return this._transformMatrix;
  62163. };
  62164. /**
  62165. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  62166. * Cube and 2D textures for instance.
  62167. */
  62168. ShadowGenerator.prototype.recreateShadowMap = function () {
  62169. var shadowMap = this._shadowMap;
  62170. if (!shadowMap) {
  62171. return;
  62172. }
  62173. // Track render list.
  62174. var renderList = shadowMap.renderList;
  62175. // Clean up existing data.
  62176. this._disposeRTTandPostProcesses();
  62177. // Reinitializes.
  62178. this._initializeGenerator();
  62179. // Reaffect the filter to ensure a correct fallback if necessary.
  62180. this.filter = this.filter;
  62181. // Reaffect the filter.
  62182. this._applyFilterValues();
  62183. // Reaffect Render List.
  62184. this._shadowMap.renderList = renderList;
  62185. };
  62186. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  62187. if (this._shadowMap2) {
  62188. this._shadowMap2.dispose();
  62189. this._shadowMap2 = null;
  62190. }
  62191. if (this._boxBlurPostprocess) {
  62192. this._boxBlurPostprocess.dispose();
  62193. this._boxBlurPostprocess = null;
  62194. }
  62195. if (this._kernelBlurXPostprocess) {
  62196. this._kernelBlurXPostprocess.dispose();
  62197. this._kernelBlurXPostprocess = null;
  62198. }
  62199. if (this._kernelBlurYPostprocess) {
  62200. this._kernelBlurYPostprocess.dispose();
  62201. this._kernelBlurYPostprocess = null;
  62202. }
  62203. this._blurPostProcesses = [];
  62204. };
  62205. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  62206. if (this._shadowMap) {
  62207. this._shadowMap.dispose();
  62208. this._shadowMap = null;
  62209. }
  62210. this._disposeBlurPostProcesses();
  62211. };
  62212. /**
  62213. * Disposes the ShadowGenerator.
  62214. * Returns nothing.
  62215. */
  62216. ShadowGenerator.prototype.dispose = function () {
  62217. this._disposeRTTandPostProcesses();
  62218. if (this._light) {
  62219. this._light._shadowGenerator = null;
  62220. this._light._markMeshesAsLightDirty();
  62221. }
  62222. };
  62223. /**
  62224. * Serializes the shadow generator setup to a json object.
  62225. * @returns The serialized JSON object
  62226. */
  62227. ShadowGenerator.prototype.serialize = function () {
  62228. var serializationObject = {};
  62229. var shadowMap = this.getShadowMap();
  62230. if (!shadowMap) {
  62231. return serializationObject;
  62232. }
  62233. serializationObject.lightId = this._light.id;
  62234. serializationObject.mapSize = shadowMap.getRenderSize();
  62235. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  62236. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  62237. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62238. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  62239. serializationObject.usePoissonSampling = this.usePoissonSampling;
  62240. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  62241. serializationObject.depthScale = this.depthScale;
  62242. serializationObject.darkness = this.getDarkness();
  62243. serializationObject.blurBoxOffset = this.blurBoxOffset;
  62244. serializationObject.blurKernel = this.blurKernel;
  62245. serializationObject.blurScale = this.blurScale;
  62246. serializationObject.useKernelBlur = this.useKernelBlur;
  62247. serializationObject.transparencyShadow = this._transparencyShadow;
  62248. serializationObject.bias = this.bias;
  62249. serializationObject.normalBias = this.normalBias;
  62250. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  62251. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  62252. serializationObject.filteringQuality = this.filteringQuality;
  62253. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  62254. serializationObject.renderList = [];
  62255. if (shadowMap.renderList) {
  62256. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  62257. var mesh = shadowMap.renderList[meshIndex];
  62258. serializationObject.renderList.push(mesh.id);
  62259. }
  62260. }
  62261. return serializationObject;
  62262. };
  62263. /**
  62264. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  62265. * @param parsedShadowGenerator The JSON object to parse
  62266. * @param scene The scene to create the shadow map for
  62267. * @returns The parsed shadow generator
  62268. */
  62269. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  62270. //casting to point light, as light is missing the position attr and typescript complains.
  62271. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  62272. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  62273. var shadowMap = shadowGenerator.getShadowMap();
  62274. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  62275. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  62276. meshes.forEach(function (mesh) {
  62277. if (!shadowMap) {
  62278. return;
  62279. }
  62280. if (!shadowMap.renderList) {
  62281. shadowMap.renderList = [];
  62282. }
  62283. shadowMap.renderList.push(mesh);
  62284. });
  62285. }
  62286. if (parsedShadowGenerator.usePoissonSampling) {
  62287. shadowGenerator.usePoissonSampling = true;
  62288. }
  62289. else if (parsedShadowGenerator.useExponentialShadowMap) {
  62290. shadowGenerator.useExponentialShadowMap = true;
  62291. }
  62292. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  62293. shadowGenerator.useBlurExponentialShadowMap = true;
  62294. }
  62295. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  62296. shadowGenerator.useCloseExponentialShadowMap = true;
  62297. }
  62298. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  62299. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  62300. }
  62301. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  62302. shadowGenerator.usePercentageCloserFiltering = true;
  62303. }
  62304. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62305. shadowGenerator.useContactHardeningShadow = true;
  62306. }
  62307. if (parsedShadowGenerator.filteringQuality) {
  62308. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62309. }
  62310. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62311. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62312. }
  62313. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62314. shadowGenerator.useExponentialShadowMap = true;
  62315. }
  62316. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62317. shadowGenerator.useBlurExponentialShadowMap = true;
  62318. }
  62319. if (parsedShadowGenerator.depthScale) {
  62320. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62321. }
  62322. if (parsedShadowGenerator.blurScale) {
  62323. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62324. }
  62325. if (parsedShadowGenerator.blurBoxOffset) {
  62326. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62327. }
  62328. if (parsedShadowGenerator.useKernelBlur) {
  62329. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62330. }
  62331. if (parsedShadowGenerator.blurKernel) {
  62332. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62333. }
  62334. if (parsedShadowGenerator.bias !== undefined) {
  62335. shadowGenerator.bias = parsedShadowGenerator.bias;
  62336. }
  62337. if (parsedShadowGenerator.normalBias !== undefined) {
  62338. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62339. }
  62340. if (parsedShadowGenerator.darkness) {
  62341. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62342. }
  62343. if (parsedShadowGenerator.transparencyShadow) {
  62344. shadowGenerator.setTransparencyShadow(true);
  62345. }
  62346. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62347. return shadowGenerator;
  62348. };
  62349. /**
  62350. * Shadow generator mode None: no filtering applied.
  62351. */
  62352. ShadowGenerator.FILTER_NONE = 0;
  62353. /**
  62354. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62355. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62356. */
  62357. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62358. /**
  62359. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62360. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62361. */
  62362. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62363. /**
  62364. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62365. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62366. */
  62367. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62368. /**
  62369. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62370. * edge artifacts on steep falloff.
  62371. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62372. */
  62373. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62374. /**
  62375. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62376. * edge artifacts on steep falloff.
  62377. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62378. */
  62379. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62380. /**
  62381. * Shadow generator mode PCF: Percentage Closer Filtering
  62382. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62383. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62384. */
  62385. ShadowGenerator.FILTER_PCF = 6;
  62386. /**
  62387. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62388. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62389. * Contact Hardening
  62390. */
  62391. ShadowGenerator.FILTER_PCSS = 7;
  62392. /**
  62393. * Reserved for PCF and PCSS
  62394. * Highest Quality.
  62395. *
  62396. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62397. *
  62398. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62399. */
  62400. ShadowGenerator.QUALITY_HIGH = 0;
  62401. /**
  62402. * Reserved for PCF and PCSS
  62403. * Good tradeoff for quality/perf cross devices
  62404. *
  62405. * Execute PCF on a 3*3 kernel.
  62406. *
  62407. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62408. */
  62409. ShadowGenerator.QUALITY_MEDIUM = 1;
  62410. /**
  62411. * Reserved for PCF and PCSS
  62412. * The lowest quality but the fastest.
  62413. *
  62414. * Execute PCF on a 1*1 kernel.
  62415. *
  62416. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62417. */
  62418. ShadowGenerator.QUALITY_LOW = 2;
  62419. return ShadowGenerator;
  62420. }());
  62421. BABYLON.ShadowGenerator = ShadowGenerator;
  62422. })(BABYLON || (BABYLON = {}));
  62423. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62424. "use strict";
  62425. var BABYLON;
  62426. (function (BABYLON) {
  62427. var DefaultLoadingScreen = /** @class */ (function () {
  62428. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62429. if (_loadingText === void 0) { _loadingText = ""; }
  62430. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62431. var _this = this;
  62432. this._renderingCanvas = _renderingCanvas;
  62433. this._loadingText = _loadingText;
  62434. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62435. // Resize
  62436. this._resizeLoadingUI = function () {
  62437. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62438. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62439. if (!_this._loadingDiv) {
  62440. return;
  62441. }
  62442. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62443. _this._loadingDiv.style.left = canvasRect.left + "px";
  62444. _this._loadingDiv.style.top = canvasRect.top + "px";
  62445. _this._loadingDiv.style.width = canvasRect.width + "px";
  62446. _this._loadingDiv.style.height = canvasRect.height + "px";
  62447. };
  62448. }
  62449. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62450. if (this._loadingDiv) {
  62451. // Do not add a loading screen if there is already one
  62452. return;
  62453. }
  62454. this._loadingDiv = document.createElement("div");
  62455. this._loadingDiv.id = "babylonjsLoadingDiv";
  62456. this._loadingDiv.style.opacity = "0";
  62457. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62458. this._loadingDiv.style.pointerEvents = "none";
  62459. // Loading text
  62460. this._loadingTextDiv = document.createElement("div");
  62461. this._loadingTextDiv.style.position = "absolute";
  62462. this._loadingTextDiv.style.left = "0";
  62463. this._loadingTextDiv.style.top = "50%";
  62464. this._loadingTextDiv.style.marginTop = "80px";
  62465. this._loadingTextDiv.style.width = "100%";
  62466. this._loadingTextDiv.style.height = "20px";
  62467. this._loadingTextDiv.style.fontFamily = "Arial";
  62468. this._loadingTextDiv.style.fontSize = "14px";
  62469. this._loadingTextDiv.style.color = "white";
  62470. this._loadingTextDiv.style.textAlign = "center";
  62471. this._loadingTextDiv.innerHTML = "Loading";
  62472. this._loadingDiv.appendChild(this._loadingTextDiv);
  62473. //set the predefined text
  62474. this._loadingTextDiv.innerHTML = this._loadingText;
  62475. // Generating keyframes
  62476. var style = document.createElement('style');
  62477. style.type = 'text/css';
  62478. 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 }";
  62479. style.innerHTML = keyFrames;
  62480. document.getElementsByTagName('head')[0].appendChild(style);
  62481. // Loading img
  62482. var imgBack = new Image();
  62483. 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";
  62484. imgBack.style.position = "absolute";
  62485. imgBack.style.left = "50%";
  62486. imgBack.style.top = "50%";
  62487. imgBack.style.marginLeft = "-60px";
  62488. imgBack.style.marginTop = "-60px";
  62489. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62490. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62491. imgBack.style.transformOrigin = "50% 50%";
  62492. imgBack.style.webkitTransformOrigin = "50% 50%";
  62493. this._loadingDiv.appendChild(imgBack);
  62494. this._resizeLoadingUI();
  62495. window.addEventListener("resize", this._resizeLoadingUI);
  62496. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62497. document.body.appendChild(this._loadingDiv);
  62498. this._loadingDiv.style.opacity = "1";
  62499. };
  62500. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62501. var _this = this;
  62502. if (!this._loadingDiv) {
  62503. return;
  62504. }
  62505. var onTransitionEnd = function () {
  62506. if (!_this._loadingDiv) {
  62507. return;
  62508. }
  62509. document.body.removeChild(_this._loadingDiv);
  62510. window.removeEventListener("resize", _this._resizeLoadingUI);
  62511. _this._loadingDiv = null;
  62512. };
  62513. this._loadingDiv.style.opacity = "0";
  62514. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62515. };
  62516. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62517. set: function (text) {
  62518. this._loadingText = text;
  62519. if (this._loadingTextDiv) {
  62520. this._loadingTextDiv.innerHTML = this._loadingText;
  62521. }
  62522. },
  62523. enumerable: true,
  62524. configurable: true
  62525. });
  62526. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62527. get: function () {
  62528. return this._loadingDivBackgroundColor;
  62529. },
  62530. set: function (color) {
  62531. this._loadingDivBackgroundColor = color;
  62532. if (!this._loadingDiv) {
  62533. return;
  62534. }
  62535. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62536. },
  62537. enumerable: true,
  62538. configurable: true
  62539. });
  62540. return DefaultLoadingScreen;
  62541. }());
  62542. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62543. })(BABYLON || (BABYLON = {}));
  62544. //# sourceMappingURL=babylon.loadingScreen.js.map
  62545. "use strict";
  62546. var BABYLON;
  62547. (function (BABYLON) {
  62548. var SceneLoaderProgressEvent = /** @class */ (function () {
  62549. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62550. this.lengthComputable = lengthComputable;
  62551. this.loaded = loaded;
  62552. this.total = total;
  62553. }
  62554. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62555. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62556. };
  62557. return SceneLoaderProgressEvent;
  62558. }());
  62559. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62560. var SceneLoader = /** @class */ (function () {
  62561. function SceneLoader() {
  62562. }
  62563. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62564. get: function () {
  62565. return 0;
  62566. },
  62567. enumerable: true,
  62568. configurable: true
  62569. });
  62570. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62571. get: function () {
  62572. return 1;
  62573. },
  62574. enumerable: true,
  62575. configurable: true
  62576. });
  62577. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62578. get: function () {
  62579. return 2;
  62580. },
  62581. enumerable: true,
  62582. configurable: true
  62583. });
  62584. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62585. get: function () {
  62586. return 3;
  62587. },
  62588. enumerable: true,
  62589. configurable: true
  62590. });
  62591. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62592. get: function () {
  62593. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62594. },
  62595. set: function (value) {
  62596. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62597. },
  62598. enumerable: true,
  62599. configurable: true
  62600. });
  62601. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62602. get: function () {
  62603. return SceneLoader._ShowLoadingScreen;
  62604. },
  62605. set: function (value) {
  62606. SceneLoader._ShowLoadingScreen = value;
  62607. },
  62608. enumerable: true,
  62609. configurable: true
  62610. });
  62611. Object.defineProperty(SceneLoader, "loggingLevel", {
  62612. get: function () {
  62613. return SceneLoader._loggingLevel;
  62614. },
  62615. set: function (value) {
  62616. SceneLoader._loggingLevel = value;
  62617. },
  62618. enumerable: true,
  62619. configurable: true
  62620. });
  62621. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62622. get: function () {
  62623. return SceneLoader._CleanBoneMatrixWeights;
  62624. },
  62625. set: function (value) {
  62626. SceneLoader._CleanBoneMatrixWeights = value;
  62627. },
  62628. enumerable: true,
  62629. configurable: true
  62630. });
  62631. SceneLoader._getDefaultPlugin = function () {
  62632. return SceneLoader._registeredPlugins[".babylon"];
  62633. };
  62634. SceneLoader._getPluginForExtension = function (extension) {
  62635. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62636. if (registeredPlugin) {
  62637. return registeredPlugin;
  62638. }
  62639. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62640. return SceneLoader._getDefaultPlugin();
  62641. };
  62642. SceneLoader._getPluginForDirectLoad = function (data) {
  62643. for (var extension in SceneLoader._registeredPlugins) {
  62644. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62645. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62646. return SceneLoader._registeredPlugins[extension];
  62647. }
  62648. }
  62649. return SceneLoader._getDefaultPlugin();
  62650. };
  62651. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62652. if (sceneFilename.name) {
  62653. sceneFilename = sceneFilename.name;
  62654. }
  62655. var queryStringPosition = sceneFilename.indexOf("?");
  62656. if (queryStringPosition !== -1) {
  62657. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62658. }
  62659. var dotPosition = sceneFilename.lastIndexOf(".");
  62660. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62661. return SceneLoader._getPluginForExtension(extension);
  62662. };
  62663. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62664. SceneLoader._getDirectLoad = function (sceneFilename) {
  62665. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62666. return sceneFilename.substr(5);
  62667. }
  62668. return null;
  62669. };
  62670. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62671. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62672. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62673. var plugin;
  62674. if (registeredPlugin.plugin.createPlugin) {
  62675. plugin = registeredPlugin.plugin.createPlugin();
  62676. }
  62677. else {
  62678. plugin = registeredPlugin.plugin;
  62679. }
  62680. var useArrayBuffer = registeredPlugin.isBinary;
  62681. var database;
  62682. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62683. var dataCallback = function (data, responseURL) {
  62684. if (scene.isDisposed) {
  62685. onError("Scene has been disposed");
  62686. return;
  62687. }
  62688. scene.database = database;
  62689. onSuccess(plugin, data, responseURL);
  62690. };
  62691. var request = null;
  62692. var pluginDisposed = false;
  62693. var onDisposeObservable = plugin.onDisposeObservable;
  62694. if (onDisposeObservable) {
  62695. onDisposeObservable.add(function () {
  62696. pluginDisposed = true;
  62697. if (request) {
  62698. request.abort();
  62699. request = null;
  62700. }
  62701. onDispose();
  62702. });
  62703. }
  62704. var manifestChecked = function () {
  62705. if (pluginDisposed) {
  62706. return;
  62707. }
  62708. var url = rootUrl + sceneFilename;
  62709. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62710. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62711. } : undefined, database, useArrayBuffer, function (request, exception) {
  62712. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62713. });
  62714. };
  62715. if (directLoad) {
  62716. dataCallback(directLoad);
  62717. return plugin;
  62718. }
  62719. if (rootUrl.indexOf("file:") === -1) {
  62720. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  62721. if (canUseOfflineSupport) {
  62722. // Also check for exceptions
  62723. var exceptionFound = false;
  62724. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  62725. var regex = _a[_i];
  62726. if (regex.test(rootUrl + sceneFilename)) {
  62727. exceptionFound = true;
  62728. break;
  62729. }
  62730. }
  62731. canUseOfflineSupport = !exceptionFound;
  62732. }
  62733. if (canUseOfflineSupport) {
  62734. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62735. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62736. }
  62737. else {
  62738. manifestChecked();
  62739. }
  62740. }
  62741. else {
  62742. var fileOrString = sceneFilename;
  62743. if (fileOrString.name) {
  62744. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62745. }
  62746. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62747. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62748. }
  62749. else {
  62750. onError("Unable to find file named " + sceneFilename);
  62751. }
  62752. }
  62753. return plugin;
  62754. };
  62755. // Public functions
  62756. SceneLoader.GetPluginForExtension = function (extension) {
  62757. return SceneLoader._getPluginForExtension(extension).plugin;
  62758. };
  62759. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62760. return !!SceneLoader._registeredPlugins[extension];
  62761. };
  62762. SceneLoader.RegisterPlugin = function (plugin) {
  62763. if (typeof plugin.extensions === "string") {
  62764. var extension = plugin.extensions;
  62765. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62766. plugin: plugin,
  62767. isBinary: false
  62768. };
  62769. }
  62770. else {
  62771. var extensions = plugin.extensions;
  62772. Object.keys(extensions).forEach(function (extension) {
  62773. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62774. plugin: plugin,
  62775. isBinary: extensions[extension].isBinary
  62776. };
  62777. });
  62778. }
  62779. };
  62780. /**
  62781. * Import meshes into a scene
  62782. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62783. * @param rootUrl a string that defines the root url for scene and resources
  62784. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62785. * @param scene the instance of BABYLON.Scene to append to
  62786. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62787. * @param onProgress a callback with a progress event for each file being loaded
  62788. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62789. * @param pluginExtension the extension used to determine the plugin
  62790. * @returns The loaded plugin
  62791. */
  62792. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62793. if (onSuccess === void 0) { onSuccess = null; }
  62794. if (onProgress === void 0) { onProgress = null; }
  62795. if (onError === void 0) { onError = null; }
  62796. if (pluginExtension === void 0) { pluginExtension = null; }
  62797. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62798. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62799. return null;
  62800. }
  62801. var loadingToken = {};
  62802. scene._addPendingData(loadingToken);
  62803. var disposeHandler = function () {
  62804. scene._removePendingData(loadingToken);
  62805. };
  62806. var errorHandler = function (message, exception) {
  62807. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62808. if (onError) {
  62809. onError(scene, errorMessage, exception);
  62810. }
  62811. else {
  62812. BABYLON.Tools.Error(errorMessage);
  62813. // should the exception be thrown?
  62814. }
  62815. disposeHandler();
  62816. };
  62817. var progressHandler = onProgress ? function (event) {
  62818. try {
  62819. onProgress(event);
  62820. }
  62821. catch (e) {
  62822. errorHandler("Error in onProgress callback", e);
  62823. }
  62824. } : undefined;
  62825. var successHandler = function (meshes, particleSystems, skeletons) {
  62826. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62827. if (onSuccess) {
  62828. try {
  62829. onSuccess(meshes, particleSystems, skeletons);
  62830. }
  62831. catch (e) {
  62832. errorHandler("Error in onSuccess callback", e);
  62833. }
  62834. }
  62835. scene._removePendingData(loadingToken);
  62836. };
  62837. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62838. if (plugin.rewriteRootURL) {
  62839. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62840. }
  62841. if (sceneFilename === "") {
  62842. if (sceneFilename === "") {
  62843. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62844. }
  62845. }
  62846. if (plugin.importMesh) {
  62847. var syncedPlugin = plugin;
  62848. var meshes = new Array();
  62849. var particleSystems = new Array();
  62850. var skeletons = new Array();
  62851. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62852. return;
  62853. }
  62854. scene.loadingPluginName = plugin.name;
  62855. successHandler(meshes, particleSystems, skeletons);
  62856. }
  62857. else {
  62858. var asyncedPlugin = plugin;
  62859. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62860. scene.loadingPluginName = plugin.name;
  62861. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62862. }).catch(function (error) {
  62863. errorHandler(error.message, error);
  62864. });
  62865. }
  62866. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62867. };
  62868. /**
  62869. * Import meshes into a scene
  62870. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62871. * @param rootUrl a string that defines the root url for scene and resources
  62872. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62873. * @param scene the instance of BABYLON.Scene to append to
  62874. * @param onProgress a callback with a progress event for each file being loaded
  62875. * @param pluginExtension the extension used to determine the plugin
  62876. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62877. */
  62878. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62879. if (onProgress === void 0) { onProgress = null; }
  62880. if (pluginExtension === void 0) { pluginExtension = null; }
  62881. return new Promise(function (resolve, reject) {
  62882. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62883. resolve({
  62884. meshes: meshes,
  62885. particleSystems: particleSystems,
  62886. skeletons: skeletons
  62887. });
  62888. }, onProgress, function (scene, message, exception) {
  62889. reject(exception || new Error(message));
  62890. });
  62891. });
  62892. };
  62893. /**
  62894. * Load a scene
  62895. * @param rootUrl a string that defines the root url for scene and resources
  62896. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62897. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62898. * @param onSuccess a callback with the scene when import succeeds
  62899. * @param onProgress a callback with a progress event for each file being loaded
  62900. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62901. * @param pluginExtension the extension used to determine the plugin
  62902. * @returns The loaded plugin
  62903. */
  62904. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62905. if (onSuccess === void 0) { onSuccess = null; }
  62906. if (onProgress === void 0) { onProgress = null; }
  62907. if (onError === void 0) { onError = null; }
  62908. if (pluginExtension === void 0) { pluginExtension = null; }
  62909. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62910. };
  62911. /**
  62912. * Load a scene
  62913. * @param rootUrl a string that defines the root url for scene and resources
  62914. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62915. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62916. * @param onProgress a callback with a progress event for each file being loaded
  62917. * @param pluginExtension the extension used to determine the plugin
  62918. * @returns The loaded scene
  62919. */
  62920. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62921. if (onProgress === void 0) { onProgress = null; }
  62922. if (pluginExtension === void 0) { pluginExtension = null; }
  62923. return new Promise(function (resolve, reject) {
  62924. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62925. resolve(scene);
  62926. }, onProgress, function (scene, message, exception) {
  62927. reject(exception || new Error(message));
  62928. }, pluginExtension);
  62929. });
  62930. };
  62931. /**
  62932. * Append a scene
  62933. * @param rootUrl a string that defines the root url for scene and resources
  62934. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62935. * @param scene is the instance of BABYLON.Scene to append to
  62936. * @param onSuccess a callback with the scene when import succeeds
  62937. * @param onProgress a callback with a progress event for each file being loaded
  62938. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62939. * @param pluginExtension the extension used to determine the plugin
  62940. * @returns The loaded plugin
  62941. */
  62942. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62943. if (onSuccess === void 0) { onSuccess = null; }
  62944. if (onProgress === void 0) { onProgress = null; }
  62945. if (onError === void 0) { onError = null; }
  62946. if (pluginExtension === void 0) { pluginExtension = null; }
  62947. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62948. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62949. return null;
  62950. }
  62951. if (SceneLoader.ShowLoadingScreen) {
  62952. scene.getEngine().displayLoadingUI();
  62953. }
  62954. var loadingToken = {};
  62955. scene._addPendingData(loadingToken);
  62956. var disposeHandler = function () {
  62957. scene._removePendingData(loadingToken);
  62958. scene.getEngine().hideLoadingUI();
  62959. };
  62960. var errorHandler = function (message, exception) {
  62961. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62962. if (onError) {
  62963. onError(scene, errorMessage, exception);
  62964. }
  62965. else {
  62966. BABYLON.Tools.Error(errorMessage);
  62967. // should the exception be thrown?
  62968. }
  62969. disposeHandler();
  62970. };
  62971. var progressHandler = onProgress ? function (event) {
  62972. try {
  62973. onProgress(event);
  62974. }
  62975. catch (e) {
  62976. errorHandler("Error in onProgress callback", e);
  62977. }
  62978. } : undefined;
  62979. var successHandler = function () {
  62980. if (onSuccess) {
  62981. try {
  62982. onSuccess(scene);
  62983. }
  62984. catch (e) {
  62985. errorHandler("Error in onSuccess callback", e);
  62986. }
  62987. }
  62988. scene._removePendingData(loadingToken);
  62989. };
  62990. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62991. if (sceneFilename === "") {
  62992. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62993. }
  62994. if (plugin.load) {
  62995. var syncedPlugin = plugin;
  62996. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62997. return;
  62998. }
  62999. scene.loadingPluginName = plugin.name;
  63000. successHandler();
  63001. }
  63002. else {
  63003. var asyncedPlugin = plugin;
  63004. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  63005. scene.loadingPluginName = plugin.name;
  63006. successHandler();
  63007. }).catch(function (error) {
  63008. errorHandler(error.message, error);
  63009. });
  63010. }
  63011. if (SceneLoader.ShowLoadingScreen) {
  63012. scene.executeWhenReady(function () {
  63013. scene.getEngine().hideLoadingUI();
  63014. });
  63015. }
  63016. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63017. };
  63018. /**
  63019. * Append a scene
  63020. * @param rootUrl a string that defines the root url for scene and resources
  63021. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63022. * @param scene is the instance of BABYLON.Scene to append to
  63023. * @param onProgress a callback with a progress event for each file being loaded
  63024. * @param pluginExtension the extension used to determine the plugin
  63025. * @returns The given scene
  63026. */
  63027. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63028. if (onProgress === void 0) { onProgress = null; }
  63029. if (pluginExtension === void 0) { pluginExtension = null; }
  63030. return new Promise(function (resolve, reject) {
  63031. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  63032. resolve(scene);
  63033. }, onProgress, function (scene, message, exception) {
  63034. reject(exception || new Error(message));
  63035. }, pluginExtension);
  63036. });
  63037. };
  63038. /**
  63039. * Load a scene into an asset container
  63040. * @param rootUrl a string that defines the root url for scene and resources
  63041. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63042. * @param scene is the instance of BABYLON.Scene to append to
  63043. * @param onSuccess a callback with the scene when import succeeds
  63044. * @param onProgress a callback with a progress event for each file being loaded
  63045. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  63046. * @param pluginExtension the extension used to determine the plugin
  63047. * @returns The loaded plugin
  63048. */
  63049. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  63050. if (onSuccess === void 0) { onSuccess = null; }
  63051. if (onProgress === void 0) { onProgress = null; }
  63052. if (onError === void 0) { onError = null; }
  63053. if (pluginExtension === void 0) { pluginExtension = null; }
  63054. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  63055. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  63056. return null;
  63057. }
  63058. var loadingToken = {};
  63059. scene._addPendingData(loadingToken);
  63060. var disposeHandler = function () {
  63061. scene._removePendingData(loadingToken);
  63062. };
  63063. var errorHandler = function (message, exception) {
  63064. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  63065. if (onError) {
  63066. onError(scene, errorMessage, exception);
  63067. }
  63068. else {
  63069. BABYLON.Tools.Error(errorMessage);
  63070. // should the exception be thrown?
  63071. }
  63072. disposeHandler();
  63073. };
  63074. var progressHandler = onProgress ? function (event) {
  63075. try {
  63076. onProgress(event);
  63077. }
  63078. catch (e) {
  63079. errorHandler("Error in onProgress callback", e);
  63080. }
  63081. } : undefined;
  63082. var successHandler = function (assets) {
  63083. if (onSuccess) {
  63084. try {
  63085. onSuccess(assets);
  63086. }
  63087. catch (e) {
  63088. errorHandler("Error in onSuccess callback", e);
  63089. }
  63090. }
  63091. scene._removePendingData(loadingToken);
  63092. };
  63093. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  63094. if (plugin.loadAssetContainer) {
  63095. var syncedPlugin = plugin;
  63096. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  63097. if (!assetContainer) {
  63098. return;
  63099. }
  63100. scene.loadingPluginName = plugin.name;
  63101. successHandler(assetContainer);
  63102. }
  63103. else if (plugin.loadAssetContainerAsync) {
  63104. var asyncedPlugin = plugin;
  63105. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  63106. scene.loadingPluginName = plugin.name;
  63107. successHandler(assetContainer);
  63108. }).catch(function (error) {
  63109. errorHandler(error.message, error);
  63110. });
  63111. }
  63112. else {
  63113. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  63114. }
  63115. if (SceneLoader.ShowLoadingScreen) {
  63116. scene.executeWhenReady(function () {
  63117. scene.getEngine().hideLoadingUI();
  63118. });
  63119. }
  63120. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  63121. };
  63122. /**
  63123. * Load a scene into an asset container
  63124. * @param rootUrl a string that defines the root url for scene and resources
  63125. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  63126. * @param scene is the instance of BABYLON.Scene to append to
  63127. * @param onProgress a callback with a progress event for each file being loaded
  63128. * @param pluginExtension the extension used to determine the plugin
  63129. * @returns The loaded asset container
  63130. */
  63131. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  63132. if (onProgress === void 0) { onProgress = null; }
  63133. if (pluginExtension === void 0) { pluginExtension = null; }
  63134. return new Promise(function (resolve, reject) {
  63135. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  63136. resolve(assetContainer);
  63137. }, onProgress, function (scene, message, exception) {
  63138. reject(exception || new Error(message));
  63139. }, pluginExtension);
  63140. });
  63141. };
  63142. // Flags
  63143. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  63144. SceneLoader._ShowLoadingScreen = true;
  63145. SceneLoader._CleanBoneMatrixWeights = false;
  63146. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  63147. // Members
  63148. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  63149. SceneLoader._registeredPlugins = {};
  63150. return SceneLoader;
  63151. }());
  63152. BABYLON.SceneLoader = SceneLoader;
  63153. ;
  63154. })(BABYLON || (BABYLON = {}));
  63155. //# sourceMappingURL=babylon.sceneLoader.js.map
  63156. "use strict";
  63157. var BABYLON;
  63158. (function (BABYLON) {
  63159. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  63160. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63161. var parsedMaterial = parsedData.materials[index];
  63162. if (parsedMaterial.id === id) {
  63163. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63164. }
  63165. }
  63166. return null;
  63167. };
  63168. var isDescendantOf = function (mesh, names, hierarchyIds) {
  63169. for (var i in names) {
  63170. if (mesh.name === names[i]) {
  63171. hierarchyIds.push(mesh.id);
  63172. return true;
  63173. }
  63174. }
  63175. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  63176. hierarchyIds.push(mesh.id);
  63177. return true;
  63178. }
  63179. return false;
  63180. };
  63181. var logOperation = function (operation, producer) {
  63182. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  63183. };
  63184. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  63185. if (addToScene === void 0) { addToScene = false; }
  63186. var container = new BABYLON.AssetContainer(scene);
  63187. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63188. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63189. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63190. // and avoid problems with multiple concurrent .babylon loads.
  63191. var log = "importScene has failed JSON parse";
  63192. try {
  63193. var parsedData = JSON.parse(data);
  63194. log = "";
  63195. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63196. var index;
  63197. var cache;
  63198. // Lights
  63199. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  63200. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  63201. var parsedLight = parsedData.lights[index];
  63202. var light = BABYLON.Light.Parse(parsedLight, scene);
  63203. if (light) {
  63204. container.lights.push(light);
  63205. log += (index === 0 ? "\n\tLights:" : "");
  63206. log += "\n\t\t" + light.toString(fullDetails);
  63207. }
  63208. }
  63209. }
  63210. // Animations
  63211. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  63212. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  63213. var parsedAnimation = parsedData.animations[index];
  63214. var animation = BABYLON.Animation.Parse(parsedAnimation);
  63215. scene.animations.push(animation);
  63216. container.animations.push(animation);
  63217. log += (index === 0 ? "\n\tAnimations:" : "");
  63218. log += "\n\t\t" + animation.toString(fullDetails);
  63219. }
  63220. }
  63221. // Materials
  63222. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  63223. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  63224. var parsedMaterial = parsedData.materials[index];
  63225. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  63226. container.materials.push(mat);
  63227. log += (index === 0 ? "\n\tMaterials:" : "");
  63228. log += "\n\t\t" + mat.toString(fullDetails);
  63229. }
  63230. }
  63231. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63232. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  63233. var parsedMultiMaterial = parsedData.multiMaterials[index];
  63234. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63235. container.multiMaterials.push(mmat);
  63236. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  63237. log += "\n\t\t" + mmat.toString(fullDetails);
  63238. }
  63239. }
  63240. // Morph targets
  63241. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  63242. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  63243. var managerData = _a[_i];
  63244. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  63245. }
  63246. }
  63247. // Skeletons
  63248. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63249. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  63250. var parsedSkeleton = parsedData.skeletons[index];
  63251. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63252. container.skeletons.push(skeleton);
  63253. log += (index === 0 ? "\n\tSkeletons:" : "");
  63254. log += "\n\t\t" + skeleton.toString(fullDetails);
  63255. }
  63256. }
  63257. // Geometries
  63258. var geometries = parsedData.geometries;
  63259. if (geometries !== undefined && geometries !== null) {
  63260. var addedGeometry = new Array();
  63261. // Boxes
  63262. var boxes = geometries.boxes;
  63263. if (boxes !== undefined && boxes !== null) {
  63264. for (index = 0, cache = boxes.length; index < cache; index++) {
  63265. var parsedBox = boxes[index];
  63266. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  63267. }
  63268. }
  63269. // Spheres
  63270. var spheres = geometries.spheres;
  63271. if (spheres !== undefined && spheres !== null) {
  63272. for (index = 0, cache = spheres.length; index < cache; index++) {
  63273. var parsedSphere = spheres[index];
  63274. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  63275. }
  63276. }
  63277. // Cylinders
  63278. var cylinders = geometries.cylinders;
  63279. if (cylinders !== undefined && cylinders !== null) {
  63280. for (index = 0, cache = cylinders.length; index < cache; index++) {
  63281. var parsedCylinder = cylinders[index];
  63282. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  63283. }
  63284. }
  63285. // Toruses
  63286. var toruses = geometries.toruses;
  63287. if (toruses !== undefined && toruses !== null) {
  63288. for (index = 0, cache = toruses.length; index < cache; index++) {
  63289. var parsedTorus = toruses[index];
  63290. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  63291. }
  63292. }
  63293. // Grounds
  63294. var grounds = geometries.grounds;
  63295. if (grounds !== undefined && grounds !== null) {
  63296. for (index = 0, cache = grounds.length; index < cache; index++) {
  63297. var parsedGround = grounds[index];
  63298. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  63299. }
  63300. }
  63301. // Planes
  63302. var planes = geometries.planes;
  63303. if (planes !== undefined && planes !== null) {
  63304. for (index = 0, cache = planes.length; index < cache; index++) {
  63305. var parsedPlane = planes[index];
  63306. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  63307. }
  63308. }
  63309. // TorusKnots
  63310. var torusKnots = geometries.torusKnots;
  63311. if (torusKnots !== undefined && torusKnots !== null) {
  63312. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  63313. var parsedTorusKnot = torusKnots[index];
  63314. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  63315. }
  63316. }
  63317. // VertexData
  63318. var vertexData = geometries.vertexData;
  63319. if (vertexData !== undefined && vertexData !== null) {
  63320. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63321. var parsedVertexData = vertexData[index];
  63322. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63323. }
  63324. }
  63325. addedGeometry.forEach(function (g) {
  63326. if (g) {
  63327. container.geometries.push(g);
  63328. }
  63329. });
  63330. }
  63331. // Transform nodes
  63332. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63333. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63334. var parsedTransformNode = parsedData.transformNodes[index];
  63335. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63336. container.transformNodes.push(node);
  63337. }
  63338. }
  63339. // Meshes
  63340. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63341. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63342. var parsedMesh = parsedData.meshes[index];
  63343. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63344. container.meshes.push(mesh);
  63345. log += (index === 0 ? "\n\tMeshes:" : "");
  63346. log += "\n\t\t" + mesh.toString(fullDetails);
  63347. }
  63348. }
  63349. // Cameras
  63350. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63351. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63352. var parsedCamera = parsedData.cameras[index];
  63353. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63354. container.cameras.push(camera);
  63355. log += (index === 0 ? "\n\tCameras:" : "");
  63356. log += "\n\t\t" + camera.toString(fullDetails);
  63357. }
  63358. }
  63359. // Browsing all the graph to connect the dots
  63360. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63361. var camera = scene.cameras[index];
  63362. if (camera._waitingParentId) {
  63363. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63364. camera._waitingParentId = null;
  63365. }
  63366. }
  63367. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63368. var light_1 = scene.lights[index];
  63369. if (light_1 && light_1._waitingParentId) {
  63370. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63371. light_1._waitingParentId = null;
  63372. }
  63373. }
  63374. // Sounds
  63375. // TODO: add sound
  63376. var loadedSounds = [];
  63377. var loadedSound;
  63378. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63379. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63380. var parsedSound = parsedData.sounds[index];
  63381. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63382. if (!parsedSound.url)
  63383. parsedSound.url = parsedSound.name;
  63384. if (!loadedSounds[parsedSound.url]) {
  63385. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63386. loadedSounds[parsedSound.url] = loadedSound;
  63387. container.sounds.push(loadedSound);
  63388. }
  63389. else {
  63390. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63391. }
  63392. }
  63393. else {
  63394. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63395. }
  63396. }
  63397. }
  63398. loadedSounds = [];
  63399. // Connect parents & children and parse actions
  63400. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63401. var transformNode = scene.transformNodes[index];
  63402. if (transformNode._waitingParentId) {
  63403. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63404. transformNode._waitingParentId = null;
  63405. }
  63406. }
  63407. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63408. var mesh = scene.meshes[index];
  63409. if (mesh._waitingParentId) {
  63410. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63411. mesh._waitingParentId = null;
  63412. }
  63413. if (mesh._waitingActions) {
  63414. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63415. mesh._waitingActions = null;
  63416. }
  63417. }
  63418. // freeze world matrix application
  63419. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63420. var currentMesh = scene.meshes[index];
  63421. if (currentMesh._waitingFreezeWorldMatrix) {
  63422. currentMesh.freezeWorldMatrix();
  63423. currentMesh._waitingFreezeWorldMatrix = null;
  63424. }
  63425. else {
  63426. currentMesh.computeWorldMatrix(true);
  63427. }
  63428. }
  63429. // Particles Systems
  63430. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63431. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63432. var parsedParticleSystem = parsedData.particleSystems[index];
  63433. if (parsedParticleSystem.activeParticleCount) {
  63434. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63435. container.particleSystems.push(ps);
  63436. }
  63437. else {
  63438. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63439. container.particleSystems.push(ps);
  63440. }
  63441. }
  63442. }
  63443. // Lens flares
  63444. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63445. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63446. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63447. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63448. container.lensFlareSystems.push(lf);
  63449. }
  63450. }
  63451. // Shadows
  63452. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63453. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63454. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63455. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63456. container.shadowGenerators.push(sg);
  63457. }
  63458. }
  63459. // Lights exclusions / inclusions
  63460. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63461. var light_2 = scene.lights[index];
  63462. // Excluded check
  63463. if (light_2._excludedMeshesIds.length > 0) {
  63464. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63465. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63466. if (excludedMesh) {
  63467. light_2.excludedMeshes.push(excludedMesh);
  63468. }
  63469. }
  63470. light_2._excludedMeshesIds = [];
  63471. }
  63472. // Included check
  63473. if (light_2._includedOnlyMeshesIds.length > 0) {
  63474. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63475. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63476. if (includedOnlyMesh) {
  63477. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63478. }
  63479. }
  63480. light_2._includedOnlyMeshesIds = [];
  63481. }
  63482. }
  63483. // Actions (scene)
  63484. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63485. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63486. }
  63487. if (!addToScene) {
  63488. container.removeAllFromScene();
  63489. }
  63490. }
  63491. catch (err) {
  63492. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63493. if (onError) {
  63494. onError(msg, err);
  63495. }
  63496. else {
  63497. BABYLON.Tools.Log(msg);
  63498. throw err;
  63499. }
  63500. }
  63501. finally {
  63502. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63503. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63504. }
  63505. }
  63506. return container;
  63507. };
  63508. BABYLON.SceneLoader.RegisterPlugin({
  63509. name: "babylon.js",
  63510. extensions: ".babylon",
  63511. canDirectLoad: function (data) {
  63512. if (data.indexOf("babylon") !== -1) {
  63513. return true;
  63514. }
  63515. return false;
  63516. },
  63517. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63518. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63519. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63520. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63521. // and avoid problems with multiple concurrent .babylon loads.
  63522. var log = "importMesh has failed JSON parse";
  63523. try {
  63524. var parsedData = JSON.parse(data);
  63525. log = "";
  63526. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63527. if (!meshesNames) {
  63528. meshesNames = null;
  63529. }
  63530. else if (!Array.isArray(meshesNames)) {
  63531. meshesNames = [meshesNames];
  63532. }
  63533. var hierarchyIds = new Array();
  63534. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63535. var loadedSkeletonsIds = [];
  63536. var loadedMaterialsIds = [];
  63537. var index;
  63538. var cache;
  63539. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63540. var parsedMesh = parsedData.meshes[index];
  63541. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63542. if (meshesNames !== null) {
  63543. // Remove found mesh name from list.
  63544. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63545. }
  63546. //Geometry?
  63547. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63548. //does the file contain geometries?
  63549. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63550. //find the correct geometry and add it to the scene
  63551. var found = false;
  63552. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63553. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63554. return;
  63555. }
  63556. else {
  63557. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63558. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63559. switch (geometryType) {
  63560. case "boxes":
  63561. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63562. break;
  63563. case "spheres":
  63564. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63565. break;
  63566. case "cylinders":
  63567. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63568. break;
  63569. case "toruses":
  63570. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63571. break;
  63572. case "grounds":
  63573. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63574. break;
  63575. case "planes":
  63576. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63577. break;
  63578. case "torusKnots":
  63579. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63580. break;
  63581. case "vertexData":
  63582. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63583. break;
  63584. }
  63585. found = true;
  63586. }
  63587. });
  63588. }
  63589. });
  63590. if (found === false) {
  63591. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63592. }
  63593. }
  63594. }
  63595. // Material ?
  63596. if (parsedMesh.materialId) {
  63597. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63598. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63599. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63600. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63601. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63602. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63603. var subMatId = parsedMultiMaterial.materials[matIndex];
  63604. loadedMaterialsIds.push(subMatId);
  63605. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63606. if (mat) {
  63607. log += "\n\tMaterial " + mat.toString(fullDetails);
  63608. }
  63609. }
  63610. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63611. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63612. if (mmat) {
  63613. materialFound = true;
  63614. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63615. }
  63616. break;
  63617. }
  63618. }
  63619. }
  63620. if (materialFound === false) {
  63621. loadedMaterialsIds.push(parsedMesh.materialId);
  63622. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63623. if (!mat) {
  63624. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63625. }
  63626. else {
  63627. log += "\n\tMaterial " + mat.toString(fullDetails);
  63628. }
  63629. }
  63630. }
  63631. // Skeleton ?
  63632. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63633. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63634. if (skeletonAlreadyLoaded === false) {
  63635. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63636. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63637. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63638. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63639. skeletons.push(skeleton);
  63640. loadedSkeletonsIds.push(parsedSkeleton.id);
  63641. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63642. }
  63643. }
  63644. }
  63645. }
  63646. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63647. meshes.push(mesh);
  63648. log += "\n\tMesh " + mesh.toString(fullDetails);
  63649. }
  63650. }
  63651. // Connecting parents
  63652. var currentMesh;
  63653. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63654. currentMesh = scene.meshes[index];
  63655. if (currentMesh._waitingParentId) {
  63656. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63657. currentMesh._waitingParentId = null;
  63658. }
  63659. }
  63660. // freeze and compute world matrix application
  63661. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63662. currentMesh = scene.meshes[index];
  63663. if (currentMesh._waitingFreezeWorldMatrix) {
  63664. currentMesh.freezeWorldMatrix();
  63665. currentMesh._waitingFreezeWorldMatrix = null;
  63666. }
  63667. else {
  63668. currentMesh.computeWorldMatrix(true);
  63669. }
  63670. }
  63671. }
  63672. // Particles
  63673. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63674. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63675. var parsedParticleSystem = parsedData.particleSystems[index];
  63676. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63677. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63678. }
  63679. }
  63680. }
  63681. return true;
  63682. }
  63683. catch (err) {
  63684. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63685. if (onError) {
  63686. onError(msg, err);
  63687. }
  63688. else {
  63689. BABYLON.Tools.Log(msg);
  63690. throw err;
  63691. }
  63692. }
  63693. finally {
  63694. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63695. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63696. }
  63697. }
  63698. return false;
  63699. },
  63700. load: function (scene, data, rootUrl, onError) {
  63701. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63702. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63703. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63704. // and avoid problems with multiple concurrent .babylon loads.
  63705. var log = "importScene has failed JSON parse";
  63706. try {
  63707. var parsedData = JSON.parse(data);
  63708. log = "";
  63709. // Scene
  63710. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63711. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63712. }
  63713. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63714. scene.autoClear = parsedData.autoClear;
  63715. }
  63716. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63717. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63718. }
  63719. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63720. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63721. }
  63722. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63723. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63724. }
  63725. // Fog
  63726. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63727. scene.fogMode = parsedData.fogMode;
  63728. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63729. scene.fogStart = parsedData.fogStart;
  63730. scene.fogEnd = parsedData.fogEnd;
  63731. scene.fogDensity = parsedData.fogDensity;
  63732. log += "\tFog mode for scene: ";
  63733. switch (scene.fogMode) {
  63734. // getters not compiling, so using hardcoded
  63735. case 1:
  63736. log += "exp\n";
  63737. break;
  63738. case 2:
  63739. log += "exp2\n";
  63740. break;
  63741. case 3:
  63742. log += "linear\n";
  63743. break;
  63744. }
  63745. }
  63746. //Physics
  63747. if (parsedData.physicsEnabled) {
  63748. var physicsPlugin;
  63749. if (parsedData.physicsEngine === "cannon") {
  63750. physicsPlugin = new BABYLON.CannonJSPlugin();
  63751. }
  63752. else if (parsedData.physicsEngine === "oimo") {
  63753. physicsPlugin = new BABYLON.OimoJSPlugin();
  63754. }
  63755. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63756. //else - default engine, which is currently oimo
  63757. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63758. scene.enablePhysics(physicsGravity, physicsPlugin);
  63759. }
  63760. // Metadata
  63761. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63762. scene.metadata = parsedData.metadata;
  63763. }
  63764. //collisions, if defined. otherwise, default is true
  63765. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63766. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63767. }
  63768. scene.workerCollisions = !!parsedData.workerCollisions;
  63769. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63770. if (!container) {
  63771. return false;
  63772. }
  63773. if (parsedData.autoAnimate) {
  63774. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63775. }
  63776. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63777. scene.setActiveCameraByID(parsedData.activeCameraID);
  63778. }
  63779. // Environment texture
  63780. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63781. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63782. if (parsedData.createDefaultSkybox === true) {
  63783. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63784. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63785. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63786. }
  63787. }
  63788. // Finish
  63789. return true;
  63790. }
  63791. catch (err) {
  63792. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63793. if (onError) {
  63794. onError(msg, err);
  63795. }
  63796. else {
  63797. BABYLON.Tools.Log(msg);
  63798. throw err;
  63799. }
  63800. }
  63801. finally {
  63802. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63803. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63804. }
  63805. }
  63806. return false;
  63807. },
  63808. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63809. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63810. return container;
  63811. }
  63812. });
  63813. })(BABYLON || (BABYLON = {}));
  63814. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63815. "use strict";
  63816. var BABYLON;
  63817. (function (BABYLON) {
  63818. var FilesInput = /** @class */ (function () {
  63819. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63820. this.onProcessFileCallback = function () { return true; };
  63821. this._engine = engine;
  63822. this._currentScene = scene;
  63823. this._sceneLoadedCallback = sceneLoadedCallback;
  63824. this._progressCallback = progressCallback;
  63825. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63826. this._textureLoadingCallback = textureLoadingCallback;
  63827. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63828. this._onReloadCallback = onReloadCallback;
  63829. this._errorCallback = errorCallback;
  63830. }
  63831. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63832. var _this = this;
  63833. if (elementToMonitor) {
  63834. this._elementToMonitor = elementToMonitor;
  63835. this._dragEnterHandler = function (e) { _this.drag(e); };
  63836. this._dragOverHandler = function (e) { _this.drag(e); };
  63837. this._dropHandler = function (e) { _this.drop(e); };
  63838. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63839. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63840. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63841. }
  63842. };
  63843. FilesInput.prototype.dispose = function () {
  63844. if (!this._elementToMonitor) {
  63845. return;
  63846. }
  63847. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63848. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63849. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63850. };
  63851. FilesInput.prototype.renderFunction = function () {
  63852. if (this._additionalRenderLoopLogicCallback) {
  63853. this._additionalRenderLoopLogicCallback();
  63854. }
  63855. if (this._currentScene) {
  63856. if (this._textureLoadingCallback) {
  63857. var remaining = this._currentScene.getWaitingItemsCount();
  63858. if (remaining > 0) {
  63859. this._textureLoadingCallback(remaining);
  63860. }
  63861. }
  63862. this._currentScene.render();
  63863. }
  63864. };
  63865. FilesInput.prototype.drag = function (e) {
  63866. e.stopPropagation();
  63867. e.preventDefault();
  63868. };
  63869. FilesInput.prototype.drop = function (eventDrop) {
  63870. eventDrop.stopPropagation();
  63871. eventDrop.preventDefault();
  63872. this.loadFiles(eventDrop);
  63873. };
  63874. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63875. var _this = this;
  63876. var reader = folder.createReader();
  63877. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63878. reader.readEntries(function (entries) {
  63879. remaining.count += entries.length;
  63880. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63881. var entry = entries_1[_i];
  63882. if (entry.isFile) {
  63883. entry.file(function (file) {
  63884. file.correctName = relativePath + file.name;
  63885. files.push(file);
  63886. if (--remaining.count === 0) {
  63887. callback();
  63888. }
  63889. });
  63890. }
  63891. else if (entry.isDirectory) {
  63892. _this._traverseFolder(entry, files, remaining, callback);
  63893. }
  63894. }
  63895. if (--remaining.count) {
  63896. callback();
  63897. }
  63898. });
  63899. };
  63900. FilesInput.prototype._processFiles = function (files) {
  63901. for (var i = 0; i < files.length; i++) {
  63902. var name = files[i].correctName.toLowerCase();
  63903. var extension = name.split('.').pop();
  63904. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63905. continue;
  63906. }
  63907. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63908. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63909. this._sceneFileToLoad = files[i];
  63910. }
  63911. else {
  63912. FilesInput.FilesToLoad[name] = files[i];
  63913. }
  63914. }
  63915. };
  63916. FilesInput.prototype.loadFiles = function (event) {
  63917. var _this = this;
  63918. if (this._startingProcessingFilesCallback)
  63919. this._startingProcessingFilesCallback();
  63920. // Handling data transfer via drag'n'drop
  63921. if (event && event.dataTransfer && event.dataTransfer.files) {
  63922. this._filesToLoad = event.dataTransfer.files;
  63923. }
  63924. // Handling files from input files
  63925. if (event && event.target && event.target.files) {
  63926. this._filesToLoad = event.target.files;
  63927. }
  63928. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63929. var files_1 = new Array();
  63930. var folders = [];
  63931. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63932. for (var i = 0; i < this._filesToLoad.length; i++) {
  63933. var fileToLoad = this._filesToLoad[i];
  63934. var name_1 = fileToLoad.name.toLowerCase();
  63935. var entry = void 0;
  63936. fileToLoad.correctName = name_1;
  63937. if (items) {
  63938. var item = items[i];
  63939. if (item.getAsEntry) {
  63940. entry = item.getAsEntry();
  63941. }
  63942. else if (item.webkitGetAsEntry) {
  63943. entry = item.webkitGetAsEntry();
  63944. }
  63945. }
  63946. if (!entry) {
  63947. files_1.push(fileToLoad);
  63948. }
  63949. else {
  63950. if (entry.isDirectory) {
  63951. folders.push(entry);
  63952. }
  63953. else {
  63954. files_1.push(fileToLoad);
  63955. }
  63956. }
  63957. }
  63958. if (folders.length === 0) {
  63959. this._processFiles(files_1);
  63960. this._processReload();
  63961. }
  63962. else {
  63963. var remaining = { count: folders.length };
  63964. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63965. var folder = folders_1[_i];
  63966. this._traverseFolder(folder, files_1, remaining, function () {
  63967. _this._processFiles(files_1);
  63968. if (remaining.count === 0) {
  63969. _this._processReload();
  63970. }
  63971. });
  63972. }
  63973. }
  63974. }
  63975. };
  63976. FilesInput.prototype._processReload = function () {
  63977. if (this._onReloadCallback) {
  63978. this._onReloadCallback(this._sceneFileToLoad);
  63979. }
  63980. else {
  63981. this.reload();
  63982. }
  63983. };
  63984. FilesInput.prototype.reload = function () {
  63985. var _this = this;
  63986. // If a scene file has been provided
  63987. if (this._sceneFileToLoad) {
  63988. if (this._currentScene) {
  63989. if (BABYLON.Tools.errorsCount > 0) {
  63990. BABYLON.Tools.ClearLogCache();
  63991. }
  63992. this._engine.stopRenderLoop();
  63993. this._currentScene.dispose();
  63994. }
  63995. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63996. if (_this._progressCallback) {
  63997. _this._progressCallback(progress);
  63998. }
  63999. }).then(function (scene) {
  64000. _this._currentScene = scene;
  64001. if (_this._sceneLoadedCallback) {
  64002. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  64003. }
  64004. // Wait for textures and shaders to be ready
  64005. _this._currentScene.executeWhenReady(function () {
  64006. _this._engine.runRenderLoop(function () {
  64007. _this.renderFunction();
  64008. });
  64009. });
  64010. }).catch(function (error) {
  64011. if (_this._errorCallback) {
  64012. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  64013. }
  64014. });
  64015. }
  64016. else {
  64017. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  64018. }
  64019. };
  64020. FilesInput.FilesToLoad = {};
  64021. return FilesInput;
  64022. }());
  64023. BABYLON.FilesInput = FilesInput;
  64024. })(BABYLON || (BABYLON = {}));
  64025. //# sourceMappingURL=babylon.filesInput.js.map
  64026. "use strict";
  64027. var BABYLON;
  64028. (function (BABYLON) {
  64029. /**
  64030. * This class implement a typical dictionary using a string as key and the generic type T as value.
  64031. * The underlying implementation relies on an associative array to ensure the best performances.
  64032. * The value can be anything including 'null' but except 'undefined'
  64033. */
  64034. var StringDictionary = /** @class */ (function () {
  64035. function StringDictionary() {
  64036. this._count = 0;
  64037. this._data = {};
  64038. }
  64039. /**
  64040. * This will clear this dictionary and copy the content from the 'source' one.
  64041. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  64042. * @param source the dictionary to take the content from and copy to this dictionary
  64043. */
  64044. StringDictionary.prototype.copyFrom = function (source) {
  64045. var _this = this;
  64046. this.clear();
  64047. source.forEach(function (t, v) { return _this.add(t, v); });
  64048. };
  64049. /**
  64050. * Get a value based from its key
  64051. * @param key the given key to get the matching value from
  64052. * @return the value if found, otherwise undefined is returned
  64053. */
  64054. StringDictionary.prototype.get = function (key) {
  64055. var val = this._data[key];
  64056. if (val !== undefined) {
  64057. return val;
  64058. }
  64059. return undefined;
  64060. };
  64061. /**
  64062. * Get a value from its key or add it if it doesn't exist.
  64063. * This method will ensure you that a given key/data will be present in the dictionary.
  64064. * @param key the given key to get the matching value from
  64065. * @param factory the factory that will create the value if the key is not present in the dictionary.
  64066. * The factory will only be invoked if there's no data for the given key.
  64067. * @return the value corresponding to the key.
  64068. */
  64069. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  64070. var val = this.get(key);
  64071. if (val !== undefined) {
  64072. return val;
  64073. }
  64074. val = factory(key);
  64075. if (val) {
  64076. this.add(key, val);
  64077. }
  64078. return val;
  64079. };
  64080. /**
  64081. * Get a value from its key if present in the dictionary otherwise add it
  64082. * @param key the key to get the value from
  64083. * @param val if there's no such key/value pair in the dictionary add it with this value
  64084. * @return the value corresponding to the key
  64085. */
  64086. StringDictionary.prototype.getOrAdd = function (key, val) {
  64087. var curVal = this.get(key);
  64088. if (curVal !== undefined) {
  64089. return curVal;
  64090. }
  64091. this.add(key, val);
  64092. return val;
  64093. };
  64094. /**
  64095. * Check if there's a given key in the dictionary
  64096. * @param key the key to check for
  64097. * @return true if the key is present, false otherwise
  64098. */
  64099. StringDictionary.prototype.contains = function (key) {
  64100. return this._data[key] !== undefined;
  64101. };
  64102. /**
  64103. * Add a new key and its corresponding value
  64104. * @param key the key to add
  64105. * @param value the value corresponding to the key
  64106. * @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
  64107. */
  64108. StringDictionary.prototype.add = function (key, value) {
  64109. if (this._data[key] !== undefined) {
  64110. return false;
  64111. }
  64112. this._data[key] = value;
  64113. ++this._count;
  64114. return true;
  64115. };
  64116. StringDictionary.prototype.set = function (key, value) {
  64117. if (this._data[key] === undefined) {
  64118. return false;
  64119. }
  64120. this._data[key] = value;
  64121. return true;
  64122. };
  64123. /**
  64124. * Get the element of the given key and remove it from the dictionary
  64125. * @param key
  64126. */
  64127. StringDictionary.prototype.getAndRemove = function (key) {
  64128. var val = this.get(key);
  64129. if (val !== undefined) {
  64130. delete this._data[key];
  64131. --this._count;
  64132. return val;
  64133. }
  64134. return null;
  64135. };
  64136. /**
  64137. * Remove a key/value from the dictionary.
  64138. * @param key the key to remove
  64139. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  64140. */
  64141. StringDictionary.prototype.remove = function (key) {
  64142. if (this.contains(key)) {
  64143. delete this._data[key];
  64144. --this._count;
  64145. return true;
  64146. }
  64147. return false;
  64148. };
  64149. /**
  64150. * Clear the whole content of the dictionary
  64151. */
  64152. StringDictionary.prototype.clear = function () {
  64153. this._data = {};
  64154. this._count = 0;
  64155. };
  64156. Object.defineProperty(StringDictionary.prototype, "count", {
  64157. get: function () {
  64158. return this._count;
  64159. },
  64160. enumerable: true,
  64161. configurable: true
  64162. });
  64163. /**
  64164. * Execute a callback on each key/val of the dictionary.
  64165. * Note that you can remove any element in this dictionary in the callback implementation
  64166. * @param callback the callback to execute on a given key/value pair
  64167. */
  64168. StringDictionary.prototype.forEach = function (callback) {
  64169. for (var cur in this._data) {
  64170. var val = this._data[cur];
  64171. callback(cur, val);
  64172. }
  64173. };
  64174. /**
  64175. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  64176. * If the callback returns null or undefined the method will iterate to the next key/value pair
  64177. * Note that you can remove any element in this dictionary in the callback implementation
  64178. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  64179. */
  64180. StringDictionary.prototype.first = function (callback) {
  64181. for (var cur in this._data) {
  64182. var val = this._data[cur];
  64183. var res = callback(cur, val);
  64184. if (res) {
  64185. return res;
  64186. }
  64187. }
  64188. return null;
  64189. };
  64190. return StringDictionary;
  64191. }());
  64192. BABYLON.StringDictionary = StringDictionary;
  64193. })(BABYLON || (BABYLON = {}));
  64194. //# sourceMappingURL=babylon.stringDictionary.js.map
  64195. "use strict";
  64196. var BABYLON;
  64197. (function (BABYLON) {
  64198. var Tags = /** @class */ (function () {
  64199. function Tags() {
  64200. }
  64201. Tags.EnableFor = function (obj) {
  64202. obj._tags = obj._tags || {};
  64203. obj.hasTags = function () {
  64204. return Tags.HasTags(obj);
  64205. };
  64206. obj.addTags = function (tagsString) {
  64207. return Tags.AddTagsTo(obj, tagsString);
  64208. };
  64209. obj.removeTags = function (tagsString) {
  64210. return Tags.RemoveTagsFrom(obj, tagsString);
  64211. };
  64212. obj.matchesTagsQuery = function (tagsQuery) {
  64213. return Tags.MatchesQuery(obj, tagsQuery);
  64214. };
  64215. };
  64216. Tags.DisableFor = function (obj) {
  64217. delete obj._tags;
  64218. delete obj.hasTags;
  64219. delete obj.addTags;
  64220. delete obj.removeTags;
  64221. delete obj.matchesTagsQuery;
  64222. };
  64223. Tags.HasTags = function (obj) {
  64224. if (!obj._tags) {
  64225. return false;
  64226. }
  64227. return !BABYLON.Tools.IsEmpty(obj._tags);
  64228. };
  64229. Tags.GetTags = function (obj, asString) {
  64230. if (asString === void 0) { asString = true; }
  64231. if (!obj._tags) {
  64232. return null;
  64233. }
  64234. if (asString) {
  64235. var tagsArray = [];
  64236. for (var tag in obj._tags) {
  64237. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  64238. tagsArray.push(tag);
  64239. }
  64240. }
  64241. return tagsArray.join(" ");
  64242. }
  64243. else {
  64244. return obj._tags;
  64245. }
  64246. };
  64247. // the tags 'true' and 'false' are reserved and cannot be used as tags
  64248. // a tag cannot start with '||', '&&', and '!'
  64249. // it cannot contain whitespaces
  64250. Tags.AddTagsTo = function (obj, tagsString) {
  64251. if (!tagsString) {
  64252. return;
  64253. }
  64254. if (typeof tagsString !== "string") {
  64255. return;
  64256. }
  64257. var tags = tagsString.split(" ");
  64258. tags.forEach(function (tag, index, array) {
  64259. Tags._AddTagTo(obj, tag);
  64260. });
  64261. };
  64262. Tags._AddTagTo = function (obj, tag) {
  64263. tag = tag.trim();
  64264. if (tag === "" || tag === "true" || tag === "false") {
  64265. return;
  64266. }
  64267. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  64268. return;
  64269. }
  64270. Tags.EnableFor(obj);
  64271. obj._tags[tag] = true;
  64272. };
  64273. Tags.RemoveTagsFrom = function (obj, tagsString) {
  64274. if (!Tags.HasTags(obj)) {
  64275. return;
  64276. }
  64277. var tags = tagsString.split(" ");
  64278. for (var t in tags) {
  64279. Tags._RemoveTagFrom(obj, tags[t]);
  64280. }
  64281. };
  64282. Tags._RemoveTagFrom = function (obj, tag) {
  64283. delete obj._tags[tag];
  64284. };
  64285. Tags.MatchesQuery = function (obj, tagsQuery) {
  64286. if (tagsQuery === undefined) {
  64287. return true;
  64288. }
  64289. if (tagsQuery === "") {
  64290. return Tags.HasTags(obj);
  64291. }
  64292. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  64293. };
  64294. return Tags;
  64295. }());
  64296. BABYLON.Tags = Tags;
  64297. })(BABYLON || (BABYLON = {}));
  64298. //# sourceMappingURL=babylon.tags.js.map
  64299. "use strict";
  64300. var BABYLON;
  64301. (function (BABYLON) {
  64302. var AndOrNotEvaluator = /** @class */ (function () {
  64303. function AndOrNotEvaluator() {
  64304. }
  64305. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  64306. if (!query.match(/\([^\(\)]*\)/g)) {
  64307. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  64308. }
  64309. else {
  64310. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  64311. // remove parenthesis
  64312. r = r.slice(1, r.length - 1);
  64313. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  64314. });
  64315. }
  64316. if (query === "true") {
  64317. return true;
  64318. }
  64319. if (query === "false") {
  64320. return false;
  64321. }
  64322. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64323. };
  64324. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64325. evaluateCallback = evaluateCallback || (function (r) {
  64326. return r === "true" ? true : false;
  64327. });
  64328. var result;
  64329. var or = parenthesisContent.split("||");
  64330. for (var i in or) {
  64331. if (or.hasOwnProperty(i)) {
  64332. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64333. var and = ori.split("&&");
  64334. if (and.length > 1) {
  64335. for (var j = 0; j < and.length; ++j) {
  64336. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64337. if (andj !== "true" && andj !== "false") {
  64338. if (andj[0] === "!") {
  64339. result = !evaluateCallback(andj.substring(1));
  64340. }
  64341. else {
  64342. result = evaluateCallback(andj);
  64343. }
  64344. }
  64345. else {
  64346. result = andj === "true" ? true : false;
  64347. }
  64348. if (!result) {
  64349. ori = "false";
  64350. break;
  64351. }
  64352. }
  64353. }
  64354. if (result || ori === "true") {
  64355. result = true;
  64356. break;
  64357. }
  64358. // result equals false (or undefined)
  64359. if (ori !== "true" && ori !== "false") {
  64360. if (ori[0] === "!") {
  64361. result = !evaluateCallback(ori.substring(1));
  64362. }
  64363. else {
  64364. result = evaluateCallback(ori);
  64365. }
  64366. }
  64367. else {
  64368. result = ori === "true" ? true : false;
  64369. }
  64370. }
  64371. }
  64372. // the whole parenthesis scope is replaced by 'true' or 'false'
  64373. return result ? "true" : "false";
  64374. };
  64375. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64376. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64377. // remove whitespaces
  64378. r = r.replace(/[\s]/g, function () { return ""; });
  64379. return r.length % 2 ? "!" : "";
  64380. });
  64381. booleanString = booleanString.trim();
  64382. if (booleanString === "!true") {
  64383. booleanString = "false";
  64384. }
  64385. else if (booleanString === "!false") {
  64386. booleanString = "true";
  64387. }
  64388. return booleanString;
  64389. };
  64390. return AndOrNotEvaluator;
  64391. }());
  64392. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64393. })(BABYLON || (BABYLON = {}));
  64394. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64395. "use strict";
  64396. var BABYLON;
  64397. (function (BABYLON) {
  64398. var Database = /** @class */ (function () {
  64399. function Database(urlToScene, callbackManifestChecked) {
  64400. // Handling various flavors of prefixed version of IndexedDB
  64401. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64402. this.callbackManifestChecked = callbackManifestChecked;
  64403. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64404. this.db = null;
  64405. this._enableSceneOffline = false;
  64406. this._enableTexturesOffline = false;
  64407. this.manifestVersionFound = 0;
  64408. this.mustUpdateRessources = false;
  64409. this.hasReachedQuota = false;
  64410. if (!Database.IDBStorageEnabled) {
  64411. this.callbackManifestChecked(true);
  64412. }
  64413. else {
  64414. this.checkManifestFile();
  64415. }
  64416. }
  64417. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64418. get: function () {
  64419. return this._enableSceneOffline;
  64420. },
  64421. enumerable: true,
  64422. configurable: true
  64423. });
  64424. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64425. get: function () {
  64426. return this._enableTexturesOffline;
  64427. },
  64428. enumerable: true,
  64429. configurable: true
  64430. });
  64431. Database.prototype.checkManifestFile = function () {
  64432. var _this = this;
  64433. var noManifestFile = function () {
  64434. _this._enableSceneOffline = false;
  64435. _this._enableTexturesOffline = false;
  64436. _this.callbackManifestChecked(false);
  64437. };
  64438. var timeStampUsed = false;
  64439. var manifestURL = this.currentSceneUrl + ".manifest";
  64440. var xhr = new XMLHttpRequest();
  64441. if (navigator.onLine) {
  64442. // Adding a timestamp to by-pass browsers' cache
  64443. timeStampUsed = true;
  64444. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64445. }
  64446. xhr.open("GET", manifestURL, true);
  64447. xhr.addEventListener("load", function () {
  64448. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64449. try {
  64450. var manifestFile = JSON.parse(xhr.response);
  64451. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64452. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64453. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64454. _this.manifestVersionFound = manifestFile.version;
  64455. }
  64456. if (_this.callbackManifestChecked) {
  64457. _this.callbackManifestChecked(true);
  64458. }
  64459. }
  64460. catch (ex) {
  64461. noManifestFile();
  64462. }
  64463. }
  64464. else {
  64465. noManifestFile();
  64466. }
  64467. }, false);
  64468. xhr.addEventListener("error", function (event) {
  64469. if (timeStampUsed) {
  64470. timeStampUsed = false;
  64471. // Let's retry without the timeStamp
  64472. // It could fail when coupled with HTML5 Offline API
  64473. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64474. xhr.open("GET", retryManifestURL, true);
  64475. xhr.send();
  64476. }
  64477. else {
  64478. noManifestFile();
  64479. }
  64480. }, false);
  64481. try {
  64482. xhr.send();
  64483. }
  64484. catch (ex) {
  64485. BABYLON.Tools.Error("Error on XHR send request.");
  64486. this.callbackManifestChecked(false);
  64487. }
  64488. };
  64489. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64490. var _this = this;
  64491. var handleError = function () {
  64492. _this.isSupported = false;
  64493. if (errorCallback)
  64494. errorCallback();
  64495. };
  64496. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64497. // Your browser doesn't support IndexedDB
  64498. this.isSupported = false;
  64499. if (errorCallback)
  64500. errorCallback();
  64501. }
  64502. else {
  64503. // If the DB hasn't been opened or created yet
  64504. if (!this.db) {
  64505. this.hasReachedQuota = false;
  64506. this.isSupported = true;
  64507. var request = this.idbFactory.open("babylonjs", 1);
  64508. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64509. request.onerror = function (event) {
  64510. handleError();
  64511. };
  64512. // executes when a version change transaction cannot complete due to other active transactions
  64513. request.onblocked = function (event) {
  64514. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64515. handleError();
  64516. };
  64517. // DB has been opened successfully
  64518. request.onsuccess = function (event) {
  64519. _this.db = request.result;
  64520. successCallback();
  64521. };
  64522. // Initialization of the DB. Creating Scenes & Textures stores
  64523. request.onupgradeneeded = function (event) {
  64524. _this.db = (event.target).result;
  64525. if (_this.db) {
  64526. try {
  64527. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64528. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64529. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64530. }
  64531. catch (ex) {
  64532. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64533. handleError();
  64534. }
  64535. }
  64536. };
  64537. }
  64538. else {
  64539. if (successCallback)
  64540. successCallback();
  64541. }
  64542. }
  64543. };
  64544. Database.prototype.loadImageFromDB = function (url, image) {
  64545. var _this = this;
  64546. var completeURL = Database.ReturnFullUrlLocation(url);
  64547. var saveAndLoadImage = function () {
  64548. if (!_this.hasReachedQuota && _this.db !== null) {
  64549. // the texture is not yet in the DB, let's try to save it
  64550. _this._saveImageIntoDBAsync(completeURL, image);
  64551. }
  64552. else {
  64553. image.src = url;
  64554. }
  64555. };
  64556. if (!this.mustUpdateRessources) {
  64557. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64558. }
  64559. else {
  64560. saveAndLoadImage();
  64561. }
  64562. };
  64563. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64564. if (this.isSupported && this.db !== null) {
  64565. var texture;
  64566. var transaction = this.db.transaction(["textures"]);
  64567. transaction.onabort = function (event) {
  64568. image.src = url;
  64569. };
  64570. transaction.oncomplete = function (event) {
  64571. var blobTextureURL;
  64572. if (texture) {
  64573. var URL = window.URL || window.webkitURL;
  64574. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64575. image.onerror = function () {
  64576. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64577. image.src = url;
  64578. };
  64579. image.src = blobTextureURL;
  64580. }
  64581. else {
  64582. notInDBCallback();
  64583. }
  64584. };
  64585. var getRequest = transaction.objectStore("textures").get(url);
  64586. getRequest.onsuccess = function (event) {
  64587. texture = (event.target).result;
  64588. };
  64589. getRequest.onerror = function (event) {
  64590. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64591. image.src = url;
  64592. };
  64593. }
  64594. else {
  64595. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64596. image.src = url;
  64597. }
  64598. };
  64599. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64600. var _this = this;
  64601. if (this.isSupported) {
  64602. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64603. var generateBlobUrl = function () {
  64604. var blobTextureURL;
  64605. if (blob) {
  64606. var URL = window.URL || window.webkitURL;
  64607. try {
  64608. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64609. }
  64610. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64611. catch (ex) {
  64612. blobTextureURL = URL.createObjectURL(blob);
  64613. }
  64614. }
  64615. if (blobTextureURL) {
  64616. image.src = blobTextureURL;
  64617. }
  64618. };
  64619. if (Database.IsUASupportingBlobStorage) {
  64620. var xhr = new XMLHttpRequest(), blob;
  64621. xhr.open("GET", url, true);
  64622. xhr.responseType = "blob";
  64623. xhr.addEventListener("load", function () {
  64624. if (xhr.status === 200 && _this.db) {
  64625. // Blob as response (XHR2)
  64626. blob = xhr.response;
  64627. var transaction = _this.db.transaction(["textures"], "readwrite");
  64628. // the transaction could abort because of a QuotaExceededError error
  64629. transaction.onabort = function (event) {
  64630. try {
  64631. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64632. var srcElement = (event.srcElement || event.target);
  64633. var error = srcElement.error;
  64634. if (error && error.name === "QuotaExceededError") {
  64635. _this.hasReachedQuota = true;
  64636. }
  64637. }
  64638. catch (ex) { }
  64639. generateBlobUrl();
  64640. };
  64641. transaction.oncomplete = function (event) {
  64642. generateBlobUrl();
  64643. };
  64644. var newTexture = { textureUrl: url, data: blob };
  64645. try {
  64646. // Put the blob into the dabase
  64647. var addRequest = transaction.objectStore("textures").put(newTexture);
  64648. addRequest.onsuccess = function (event) {
  64649. };
  64650. addRequest.onerror = function (event) {
  64651. generateBlobUrl();
  64652. };
  64653. }
  64654. catch (ex) {
  64655. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64656. if (ex.code === 25) {
  64657. Database.IsUASupportingBlobStorage = false;
  64658. }
  64659. image.src = url;
  64660. }
  64661. }
  64662. else {
  64663. image.src = url;
  64664. }
  64665. }, false);
  64666. xhr.addEventListener("error", function (event) {
  64667. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64668. image.src = url;
  64669. }, false);
  64670. xhr.send();
  64671. }
  64672. else {
  64673. image.src = url;
  64674. }
  64675. }
  64676. else {
  64677. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64678. image.src = url;
  64679. }
  64680. };
  64681. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64682. var _this = this;
  64683. var updateVersion = function () {
  64684. // the version is not yet in the DB or we need to update it
  64685. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64686. };
  64687. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64688. };
  64689. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64690. var _this = this;
  64691. if (this.isSupported && this.db) {
  64692. var version;
  64693. try {
  64694. var transaction = this.db.transaction(["versions"]);
  64695. transaction.oncomplete = function (event) {
  64696. if (version) {
  64697. // If the version in the JSON file is > than the version in DB
  64698. if (_this.manifestVersionFound > version.data) {
  64699. _this.mustUpdateRessources = true;
  64700. updateInDBCallback();
  64701. }
  64702. else {
  64703. callback(version.data);
  64704. }
  64705. }
  64706. else {
  64707. _this.mustUpdateRessources = true;
  64708. updateInDBCallback();
  64709. }
  64710. };
  64711. transaction.onabort = function (event) {
  64712. callback(-1);
  64713. };
  64714. var getRequest = transaction.objectStore("versions").get(url);
  64715. getRequest.onsuccess = function (event) {
  64716. version = (event.target).result;
  64717. };
  64718. getRequest.onerror = function (event) {
  64719. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64720. callback(-1);
  64721. };
  64722. }
  64723. catch (ex) {
  64724. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64725. callback(-1);
  64726. }
  64727. }
  64728. else {
  64729. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64730. callback(-1);
  64731. }
  64732. };
  64733. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64734. var _this = this;
  64735. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64736. try {
  64737. // Open a transaction to the database
  64738. var transaction = this.db.transaction(["versions"], "readwrite");
  64739. // the transaction could abort because of a QuotaExceededError error
  64740. transaction.onabort = function (event) {
  64741. try {
  64742. var error = event.srcElement['error'];
  64743. if (error && error.name === "QuotaExceededError") {
  64744. _this.hasReachedQuota = true;
  64745. }
  64746. }
  64747. catch (ex) { }
  64748. callback(-1);
  64749. };
  64750. transaction.oncomplete = function (event) {
  64751. callback(_this.manifestVersionFound);
  64752. };
  64753. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64754. // Put the scene into the database
  64755. var addRequest = transaction.objectStore("versions").put(newVersion);
  64756. addRequest.onsuccess = function (event) {
  64757. };
  64758. addRequest.onerror = function (event) {
  64759. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64760. };
  64761. }
  64762. catch (ex) {
  64763. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64764. callback(-1);
  64765. }
  64766. }
  64767. else {
  64768. callback(-1);
  64769. }
  64770. };
  64771. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64772. var _this = this;
  64773. var completeUrl = Database.ReturnFullUrlLocation(url);
  64774. var saveAndLoadFile = function () {
  64775. // the scene is not yet in the DB, let's try to save it
  64776. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64777. };
  64778. this._checkVersionFromDB(completeUrl, function (version) {
  64779. if (version !== -1) {
  64780. if (!_this.mustUpdateRessources) {
  64781. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64782. }
  64783. else {
  64784. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64785. }
  64786. }
  64787. else {
  64788. if (errorCallback) {
  64789. errorCallback();
  64790. }
  64791. }
  64792. });
  64793. };
  64794. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64795. if (this.isSupported && this.db) {
  64796. var targetStore;
  64797. if (url.indexOf(".babylon") !== -1) {
  64798. targetStore = "scenes";
  64799. }
  64800. else {
  64801. targetStore = "textures";
  64802. }
  64803. var file;
  64804. var transaction = this.db.transaction([targetStore]);
  64805. transaction.oncomplete = function (event) {
  64806. if (file) {
  64807. callback(file.data);
  64808. }
  64809. else {
  64810. notInDBCallback();
  64811. }
  64812. };
  64813. transaction.onabort = function (event) {
  64814. notInDBCallback();
  64815. };
  64816. var getRequest = transaction.objectStore(targetStore).get(url);
  64817. getRequest.onsuccess = function (event) {
  64818. file = (event.target).result;
  64819. };
  64820. getRequest.onerror = function (event) {
  64821. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64822. notInDBCallback();
  64823. };
  64824. }
  64825. else {
  64826. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64827. callback();
  64828. }
  64829. };
  64830. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64831. var _this = this;
  64832. if (this.isSupported) {
  64833. var targetStore;
  64834. if (url.indexOf(".babylon") !== -1) {
  64835. targetStore = "scenes";
  64836. }
  64837. else {
  64838. targetStore = "textures";
  64839. }
  64840. // Create XHR
  64841. var xhr = new XMLHttpRequest();
  64842. var fileData;
  64843. xhr.open("GET", url, true);
  64844. if (useArrayBuffer) {
  64845. xhr.responseType = "arraybuffer";
  64846. }
  64847. if (progressCallback) {
  64848. xhr.onprogress = progressCallback;
  64849. }
  64850. xhr.addEventListener("load", function () {
  64851. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64852. // Blob as response (XHR2)
  64853. //fileData = xhr.responseText;
  64854. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64855. if (!_this.hasReachedQuota && _this.db) {
  64856. // Open a transaction to the database
  64857. var transaction = _this.db.transaction([targetStore], "readwrite");
  64858. // the transaction could abort because of a QuotaExceededError error
  64859. transaction.onabort = function (event) {
  64860. try {
  64861. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64862. var error = event.srcElement['error'];
  64863. if (error && error.name === "QuotaExceededError") {
  64864. _this.hasReachedQuota = true;
  64865. }
  64866. }
  64867. catch (ex) { }
  64868. callback(fileData);
  64869. };
  64870. transaction.oncomplete = function (event) {
  64871. callback(fileData);
  64872. };
  64873. var newFile;
  64874. if (targetStore === "scenes") {
  64875. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64876. }
  64877. else {
  64878. newFile = { textureUrl: url, data: fileData };
  64879. }
  64880. try {
  64881. // Put the scene into the database
  64882. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64883. addRequest.onsuccess = function (event) {
  64884. };
  64885. addRequest.onerror = function (event) {
  64886. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64887. };
  64888. }
  64889. catch (ex) {
  64890. callback(fileData);
  64891. }
  64892. }
  64893. else {
  64894. callback(fileData);
  64895. }
  64896. }
  64897. else {
  64898. callback();
  64899. }
  64900. }, false);
  64901. xhr.addEventListener("error", function (event) {
  64902. BABYLON.Tools.Error("error on XHR request.");
  64903. callback();
  64904. }, false);
  64905. xhr.send();
  64906. }
  64907. else {
  64908. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64909. callback();
  64910. }
  64911. };
  64912. Database.IsUASupportingBlobStorage = true;
  64913. Database.IDBStorageEnabled = true;
  64914. Database.parseURL = function (url) {
  64915. var a = document.createElement('a');
  64916. a.href = url;
  64917. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64918. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64919. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64920. return absLocation;
  64921. };
  64922. Database.ReturnFullUrlLocation = function (url) {
  64923. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64924. return (Database.parseURL(window.location.href) + url);
  64925. }
  64926. else {
  64927. return url;
  64928. }
  64929. };
  64930. return Database;
  64931. }());
  64932. BABYLON.Database = Database;
  64933. })(BABYLON || (BABYLON = {}));
  64934. //# sourceMappingURL=babylon.database.js.map
  64935. "use strict";
  64936. var BABYLON;
  64937. (function (BABYLON) {
  64938. var FresnelParameters = /** @class */ (function () {
  64939. function FresnelParameters() {
  64940. this._isEnabled = true;
  64941. this.leftColor = BABYLON.Color3.White();
  64942. this.rightColor = BABYLON.Color3.Black();
  64943. this.bias = 0;
  64944. this.power = 1;
  64945. }
  64946. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64947. get: function () {
  64948. return this._isEnabled;
  64949. },
  64950. set: function (value) {
  64951. if (this._isEnabled === value) {
  64952. return;
  64953. }
  64954. this._isEnabled = value;
  64955. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64956. },
  64957. enumerable: true,
  64958. configurable: true
  64959. });
  64960. FresnelParameters.prototype.clone = function () {
  64961. var newFresnelParameters = new FresnelParameters();
  64962. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64963. return newFresnelParameters;
  64964. };
  64965. FresnelParameters.prototype.serialize = function () {
  64966. var serializationObject = {};
  64967. serializationObject.isEnabled = this.isEnabled;
  64968. serializationObject.leftColor = this.leftColor.asArray();
  64969. serializationObject.rightColor = this.rightColor.asArray();
  64970. serializationObject.bias = this.bias;
  64971. serializationObject.power = this.power;
  64972. return serializationObject;
  64973. };
  64974. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64975. var fresnelParameters = new FresnelParameters();
  64976. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64977. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64978. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64979. fresnelParameters.bias = parsedFresnelParameters.bias;
  64980. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64981. return fresnelParameters;
  64982. };
  64983. return FresnelParameters;
  64984. }());
  64985. BABYLON.FresnelParameters = FresnelParameters;
  64986. })(BABYLON || (BABYLON = {}));
  64987. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64988. "use strict";
  64989. var BABYLON;
  64990. (function (BABYLON) {
  64991. var MultiMaterial = /** @class */ (function (_super) {
  64992. __extends(MultiMaterial, _super);
  64993. function MultiMaterial(name, scene) {
  64994. var _this = _super.call(this, name, scene, true) || this;
  64995. scene.multiMaterials.push(_this);
  64996. _this.subMaterials = new Array();
  64997. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64998. return _this;
  64999. }
  65000. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  65001. get: function () {
  65002. return this._subMaterials;
  65003. },
  65004. set: function (value) {
  65005. this._subMaterials = value;
  65006. this._hookArray(value);
  65007. },
  65008. enumerable: true,
  65009. configurable: true
  65010. });
  65011. MultiMaterial.prototype._hookArray = function (array) {
  65012. var _this = this;
  65013. var oldPush = array.push;
  65014. array.push = function () {
  65015. var items = [];
  65016. for (var _i = 0; _i < arguments.length; _i++) {
  65017. items[_i] = arguments[_i];
  65018. }
  65019. var result = oldPush.apply(array, items);
  65020. _this._markAllSubMeshesAsTexturesDirty();
  65021. return result;
  65022. };
  65023. var oldSplice = array.splice;
  65024. array.splice = function (index, deleteCount) {
  65025. var deleted = oldSplice.apply(array, [index, deleteCount]);
  65026. _this._markAllSubMeshesAsTexturesDirty();
  65027. return deleted;
  65028. };
  65029. };
  65030. // Properties
  65031. MultiMaterial.prototype.getSubMaterial = function (index) {
  65032. if (index < 0 || index >= this.subMaterials.length) {
  65033. return this.getScene().defaultMaterial;
  65034. }
  65035. return this.subMaterials[index];
  65036. };
  65037. MultiMaterial.prototype.getActiveTextures = function () {
  65038. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  65039. if (subMaterial) {
  65040. return subMaterial.getActiveTextures();
  65041. }
  65042. else {
  65043. return [];
  65044. }
  65045. }));
  65046. var _a;
  65047. };
  65048. // Methods
  65049. MultiMaterial.prototype.getClassName = function () {
  65050. return "MultiMaterial";
  65051. };
  65052. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  65053. for (var index = 0; index < this.subMaterials.length; index++) {
  65054. var subMaterial = this.subMaterials[index];
  65055. if (subMaterial) {
  65056. if (subMaterial.storeEffectOnSubMeshes) {
  65057. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  65058. return false;
  65059. }
  65060. continue;
  65061. }
  65062. if (!subMaterial.isReady(mesh)) {
  65063. return false;
  65064. }
  65065. }
  65066. }
  65067. return true;
  65068. };
  65069. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  65070. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  65071. for (var index = 0; index < this.subMaterials.length; index++) {
  65072. var subMaterial = null;
  65073. var current = this.subMaterials[index];
  65074. if (cloneChildren && current) {
  65075. subMaterial = current.clone(name + "-" + current.name);
  65076. }
  65077. else {
  65078. subMaterial = this.subMaterials[index];
  65079. }
  65080. newMultiMaterial.subMaterials.push(subMaterial);
  65081. }
  65082. return newMultiMaterial;
  65083. };
  65084. MultiMaterial.prototype.serialize = function () {
  65085. var serializationObject = {};
  65086. serializationObject.name = this.name;
  65087. serializationObject.id = this.id;
  65088. if (BABYLON.Tags) {
  65089. serializationObject.tags = BABYLON.Tags.GetTags(this);
  65090. }
  65091. serializationObject.materials = [];
  65092. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  65093. var subMat = this.subMaterials[matIndex];
  65094. if (subMat) {
  65095. serializationObject.materials.push(subMat.id);
  65096. }
  65097. else {
  65098. serializationObject.materials.push(null);
  65099. }
  65100. }
  65101. return serializationObject;
  65102. };
  65103. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  65104. var scene = this.getScene();
  65105. if (!scene) {
  65106. return;
  65107. }
  65108. var index = scene.multiMaterials.indexOf(this);
  65109. if (index >= 0) {
  65110. scene.multiMaterials.splice(index, 1);
  65111. }
  65112. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  65113. };
  65114. return MultiMaterial;
  65115. }(BABYLON.Material));
  65116. BABYLON.MultiMaterial = MultiMaterial;
  65117. })(BABYLON || (BABYLON = {}));
  65118. //# sourceMappingURL=babylon.multiMaterial.js.map
  65119. "use strict";
  65120. var BABYLON;
  65121. (function (BABYLON) {
  65122. var FreeCameraTouchInput = /** @class */ (function () {
  65123. function FreeCameraTouchInput() {
  65124. this._offsetX = null;
  65125. this._offsetY = null;
  65126. this._pointerPressed = new Array();
  65127. this.touchAngularSensibility = 200000.0;
  65128. this.touchMoveSensibility = 250.0;
  65129. }
  65130. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  65131. var _this = this;
  65132. var previousPosition = null;
  65133. if (this._pointerInput === undefined) {
  65134. this._onLostFocus = function (evt) {
  65135. _this._offsetX = null;
  65136. _this._offsetY = null;
  65137. };
  65138. this._pointerInput = function (p, s) {
  65139. var evt = p.event;
  65140. if (evt.pointerType === "mouse") {
  65141. return;
  65142. }
  65143. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  65144. if (!noPreventDefault) {
  65145. evt.preventDefault();
  65146. }
  65147. _this._pointerPressed.push(evt.pointerId);
  65148. if (_this._pointerPressed.length !== 1) {
  65149. return;
  65150. }
  65151. previousPosition = {
  65152. x: evt.clientX,
  65153. y: evt.clientY
  65154. };
  65155. }
  65156. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  65157. if (!noPreventDefault) {
  65158. evt.preventDefault();
  65159. }
  65160. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65161. if (index === -1) {
  65162. return;
  65163. }
  65164. _this._pointerPressed.splice(index, 1);
  65165. if (index != 0) {
  65166. return;
  65167. }
  65168. previousPosition = null;
  65169. _this._offsetX = null;
  65170. _this._offsetY = null;
  65171. }
  65172. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  65173. if (!noPreventDefault) {
  65174. evt.preventDefault();
  65175. }
  65176. if (!previousPosition) {
  65177. return;
  65178. }
  65179. var index = _this._pointerPressed.indexOf(evt.pointerId);
  65180. if (index != 0) {
  65181. return;
  65182. }
  65183. _this._offsetX = evt.clientX - previousPosition.x;
  65184. _this._offsetY = -(evt.clientY - previousPosition.y);
  65185. }
  65186. };
  65187. }
  65188. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  65189. if (this._onLostFocus) {
  65190. element.addEventListener("blur", this._onLostFocus);
  65191. }
  65192. };
  65193. FreeCameraTouchInput.prototype.detachControl = function (element) {
  65194. if (this._pointerInput && element) {
  65195. if (this._observer) {
  65196. this.camera.getScene().onPointerObservable.remove(this._observer);
  65197. this._observer = null;
  65198. }
  65199. if (this._onLostFocus) {
  65200. element.removeEventListener("blur", this._onLostFocus);
  65201. this._onLostFocus = null;
  65202. }
  65203. this._pointerPressed = [];
  65204. this._offsetX = null;
  65205. this._offsetY = null;
  65206. }
  65207. };
  65208. FreeCameraTouchInput.prototype.checkInputs = function () {
  65209. if (this._offsetX && this._offsetY) {
  65210. var camera = this.camera;
  65211. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  65212. if (this._pointerPressed.length > 1) {
  65213. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  65214. }
  65215. else {
  65216. var speed = camera._computeLocalCameraSpeed();
  65217. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  65218. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  65219. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  65220. }
  65221. }
  65222. };
  65223. FreeCameraTouchInput.prototype.getClassName = function () {
  65224. return "FreeCameraTouchInput";
  65225. };
  65226. FreeCameraTouchInput.prototype.getSimpleName = function () {
  65227. return "touch";
  65228. };
  65229. __decorate([
  65230. BABYLON.serialize()
  65231. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  65232. __decorate([
  65233. BABYLON.serialize()
  65234. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  65235. return FreeCameraTouchInput;
  65236. }());
  65237. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  65238. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  65239. })(BABYLON || (BABYLON = {}));
  65240. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  65241. "use strict";
  65242. var BABYLON;
  65243. (function (BABYLON) {
  65244. // We're mainly based on the logic defined into the FreeCamera code
  65245. var TouchCamera = /** @class */ (function (_super) {
  65246. __extends(TouchCamera, _super);
  65247. //-- end properties for backward compatibility for inputs
  65248. function TouchCamera(name, position, scene) {
  65249. var _this = _super.call(this, name, position, scene) || this;
  65250. _this.inputs.addTouch();
  65251. _this._setupInputs();
  65252. return _this;
  65253. }
  65254. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  65255. //-- Begin properties for backward compatibility for inputs
  65256. get: function () {
  65257. var touch = this.inputs.attached["touch"];
  65258. if (touch)
  65259. return touch.touchAngularSensibility;
  65260. return 0;
  65261. },
  65262. set: function (value) {
  65263. var touch = this.inputs.attached["touch"];
  65264. if (touch)
  65265. touch.touchAngularSensibility = value;
  65266. },
  65267. enumerable: true,
  65268. configurable: true
  65269. });
  65270. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  65271. get: function () {
  65272. var touch = this.inputs.attached["touch"];
  65273. if (touch)
  65274. return touch.touchMoveSensibility;
  65275. return 0;
  65276. },
  65277. set: function (value) {
  65278. var touch = this.inputs.attached["touch"];
  65279. if (touch)
  65280. touch.touchMoveSensibility = value;
  65281. },
  65282. enumerable: true,
  65283. configurable: true
  65284. });
  65285. TouchCamera.prototype.getClassName = function () {
  65286. return "TouchCamera";
  65287. };
  65288. TouchCamera.prototype._setupInputs = function () {
  65289. var mouse = this.inputs.attached["mouse"];
  65290. if (mouse) {
  65291. mouse.touchEnabled = false;
  65292. }
  65293. };
  65294. return TouchCamera;
  65295. }(BABYLON.FreeCamera));
  65296. BABYLON.TouchCamera = TouchCamera;
  65297. })(BABYLON || (BABYLON = {}));
  65298. //# sourceMappingURL=babylon.touchCamera.js.map
  65299. "use strict";
  65300. var BABYLON;
  65301. (function (BABYLON) {
  65302. var ProceduralTexture = /** @class */ (function (_super) {
  65303. __extends(ProceduralTexture, _super);
  65304. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  65305. if (fallbackTexture === void 0) { fallbackTexture = null; }
  65306. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65307. if (isCube === void 0) { isCube = false; }
  65308. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  65309. _this.isCube = isCube;
  65310. _this.isEnabled = true;
  65311. _this._currentRefreshId = -1;
  65312. _this._refreshRate = 1;
  65313. _this._vertexBuffers = {};
  65314. _this._uniforms = new Array();
  65315. _this._samplers = new Array();
  65316. _this._textures = {};
  65317. _this._floats = {};
  65318. _this._floatsArrays = {};
  65319. _this._colors3 = {};
  65320. _this._colors4 = {};
  65321. _this._vectors2 = {};
  65322. _this._vectors3 = {};
  65323. _this._matrices = {};
  65324. _this._fallbackTextureUsed = false;
  65325. scene._proceduralTextures.push(_this);
  65326. _this._engine = scene.getEngine();
  65327. _this.name = name;
  65328. _this.isRenderTarget = true;
  65329. _this._size = size;
  65330. _this._generateMipMaps = generateMipMaps;
  65331. _this.setFragment(fragment);
  65332. _this._fallbackTexture = fallbackTexture;
  65333. if (isCube) {
  65334. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65335. _this.setFloat("face", 0);
  65336. }
  65337. else {
  65338. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65339. }
  65340. // VBO
  65341. var vertices = [];
  65342. vertices.push(1, 1);
  65343. vertices.push(-1, 1);
  65344. vertices.push(-1, -1);
  65345. vertices.push(1, -1);
  65346. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65347. _this._createIndexBuffer();
  65348. return _this;
  65349. }
  65350. ProceduralTexture.prototype._createIndexBuffer = function () {
  65351. var engine = this._engine;
  65352. // Indices
  65353. var indices = [];
  65354. indices.push(0);
  65355. indices.push(1);
  65356. indices.push(2);
  65357. indices.push(0);
  65358. indices.push(2);
  65359. indices.push(3);
  65360. this._indexBuffer = engine.createIndexBuffer(indices);
  65361. };
  65362. ProceduralTexture.prototype._rebuild = function () {
  65363. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65364. if (vb) {
  65365. vb._rebuild();
  65366. }
  65367. this._createIndexBuffer();
  65368. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65369. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65370. }
  65371. };
  65372. ProceduralTexture.prototype.reset = function () {
  65373. if (this._effect === undefined) {
  65374. return;
  65375. }
  65376. var engine = this._engine;
  65377. engine._releaseEffect(this._effect);
  65378. };
  65379. ProceduralTexture.prototype.isReady = function () {
  65380. var _this = this;
  65381. var engine = this._engine;
  65382. var shaders;
  65383. if (!this._fragment) {
  65384. return false;
  65385. }
  65386. if (this._fallbackTextureUsed) {
  65387. return true;
  65388. }
  65389. if (this._fragment.fragmentElement !== undefined) {
  65390. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65391. }
  65392. else {
  65393. shaders = { vertex: "procedural", fragment: this._fragment };
  65394. }
  65395. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65396. _this.releaseInternalTexture();
  65397. if (_this._fallbackTexture) {
  65398. _this._texture = _this._fallbackTexture._texture;
  65399. if (_this._texture) {
  65400. _this._texture.incrementReferences();
  65401. }
  65402. }
  65403. _this._fallbackTextureUsed = true;
  65404. });
  65405. return this._effect.isReady();
  65406. };
  65407. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65408. this._currentRefreshId = -1;
  65409. };
  65410. ProceduralTexture.prototype.setFragment = function (fragment) {
  65411. this._fragment = fragment;
  65412. };
  65413. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65414. get: function () {
  65415. return this._refreshRate;
  65416. },
  65417. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65418. set: function (value) {
  65419. this._refreshRate = value;
  65420. this.resetRefreshCounter();
  65421. },
  65422. enumerable: true,
  65423. configurable: true
  65424. });
  65425. ProceduralTexture.prototype._shouldRender = function () {
  65426. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65427. return false;
  65428. }
  65429. if (this._fallbackTextureUsed) {
  65430. return false;
  65431. }
  65432. if (this._currentRefreshId === -1) {
  65433. this._currentRefreshId = 1;
  65434. return true;
  65435. }
  65436. if (this.refreshRate === this._currentRefreshId) {
  65437. this._currentRefreshId = 1;
  65438. return true;
  65439. }
  65440. this._currentRefreshId++;
  65441. return false;
  65442. };
  65443. ProceduralTexture.prototype.getRenderSize = function () {
  65444. return this._size;
  65445. };
  65446. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65447. if (this._fallbackTextureUsed) {
  65448. return;
  65449. }
  65450. this.releaseInternalTexture();
  65451. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65452. };
  65453. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65454. if (this._uniforms.indexOf(uniformName) === -1) {
  65455. this._uniforms.push(uniformName);
  65456. }
  65457. };
  65458. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65459. if (this._samplers.indexOf(name) === -1) {
  65460. this._samplers.push(name);
  65461. }
  65462. this._textures[name] = texture;
  65463. return this;
  65464. };
  65465. ProceduralTexture.prototype.setFloat = function (name, value) {
  65466. this._checkUniform(name);
  65467. this._floats[name] = value;
  65468. return this;
  65469. };
  65470. ProceduralTexture.prototype.setFloats = function (name, value) {
  65471. this._checkUniform(name);
  65472. this._floatsArrays[name] = value;
  65473. return this;
  65474. };
  65475. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65476. this._checkUniform(name);
  65477. this._colors3[name] = value;
  65478. return this;
  65479. };
  65480. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65481. this._checkUniform(name);
  65482. this._colors4[name] = value;
  65483. return this;
  65484. };
  65485. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65486. this._checkUniform(name);
  65487. this._vectors2[name] = value;
  65488. return this;
  65489. };
  65490. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65491. this._checkUniform(name);
  65492. this._vectors3[name] = value;
  65493. return this;
  65494. };
  65495. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65496. this._checkUniform(name);
  65497. this._matrices[name] = value;
  65498. return this;
  65499. };
  65500. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65501. var scene = this.getScene();
  65502. if (!scene) {
  65503. return;
  65504. }
  65505. var engine = this._engine;
  65506. // Render
  65507. engine.enableEffect(this._effect);
  65508. engine.setState(false);
  65509. // Texture
  65510. for (var name in this._textures) {
  65511. this._effect.setTexture(name, this._textures[name]);
  65512. }
  65513. // Float
  65514. for (name in this._floats) {
  65515. this._effect.setFloat(name, this._floats[name]);
  65516. }
  65517. // Floats
  65518. for (name in this._floatsArrays) {
  65519. this._effect.setArray(name, this._floatsArrays[name]);
  65520. }
  65521. // Color3
  65522. for (name in this._colors3) {
  65523. this._effect.setColor3(name, this._colors3[name]);
  65524. }
  65525. // Color4
  65526. for (name in this._colors4) {
  65527. var color = this._colors4[name];
  65528. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65529. }
  65530. // Vector2
  65531. for (name in this._vectors2) {
  65532. this._effect.setVector2(name, this._vectors2[name]);
  65533. }
  65534. // Vector3
  65535. for (name in this._vectors3) {
  65536. this._effect.setVector3(name, this._vectors3[name]);
  65537. }
  65538. // Matrix
  65539. for (name in this._matrices) {
  65540. this._effect.setMatrix(name, this._matrices[name]);
  65541. }
  65542. if (!this._texture) {
  65543. return;
  65544. }
  65545. if (this.isCube) {
  65546. for (var face = 0; face < 6; face++) {
  65547. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65548. // VBOs
  65549. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65550. this._effect.setFloat("face", face);
  65551. // Clear
  65552. engine.clear(scene.clearColor, true, true, true);
  65553. // Draw order
  65554. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65555. // Mipmaps
  65556. if (face === 5) {
  65557. engine.generateMipMapsForCubemap(this._texture);
  65558. }
  65559. }
  65560. }
  65561. else {
  65562. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65563. // VBOs
  65564. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65565. // Clear
  65566. engine.clear(scene.clearColor, true, true, true);
  65567. // Draw order
  65568. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65569. }
  65570. // Unbind
  65571. engine.unBindFramebuffer(this._texture, this.isCube);
  65572. if (this.onGenerated) {
  65573. this.onGenerated();
  65574. }
  65575. };
  65576. ProceduralTexture.prototype.clone = function () {
  65577. var textureSize = this.getSize();
  65578. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65579. // Base texture
  65580. newTexture.hasAlpha = this.hasAlpha;
  65581. newTexture.level = this.level;
  65582. // RenderTarget Texture
  65583. newTexture.coordinatesMode = this.coordinatesMode;
  65584. return newTexture;
  65585. };
  65586. ProceduralTexture.prototype.dispose = function () {
  65587. var scene = this.getScene();
  65588. if (!scene) {
  65589. return;
  65590. }
  65591. var index = scene._proceduralTextures.indexOf(this);
  65592. if (index >= 0) {
  65593. scene._proceduralTextures.splice(index, 1);
  65594. }
  65595. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65596. if (vertexBuffer) {
  65597. vertexBuffer.dispose();
  65598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65599. }
  65600. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65601. this._indexBuffer = null;
  65602. }
  65603. _super.prototype.dispose.call(this);
  65604. };
  65605. return ProceduralTexture;
  65606. }(BABYLON.Texture));
  65607. BABYLON.ProceduralTexture = ProceduralTexture;
  65608. })(BABYLON || (BABYLON = {}));
  65609. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65610. "use strict";
  65611. var BABYLON;
  65612. (function (BABYLON) {
  65613. var CustomProceduralTexture = /** @class */ (function (_super) {
  65614. __extends(CustomProceduralTexture, _super);
  65615. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65616. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65617. _this._animate = true;
  65618. _this._time = 0;
  65619. _this._texturePath = texturePath;
  65620. //Try to load json
  65621. _this.loadJson(texturePath);
  65622. _this.refreshRate = 1;
  65623. return _this;
  65624. }
  65625. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65626. var _this = this;
  65627. var noConfigFile = function () {
  65628. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65629. try {
  65630. _this.setFragment(_this._texturePath);
  65631. }
  65632. catch (ex) {
  65633. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65634. }
  65635. };
  65636. var configFileUrl = jsonUrl + "/config.json";
  65637. var xhr = new XMLHttpRequest();
  65638. xhr.open("GET", configFileUrl, true);
  65639. xhr.addEventListener("load", function () {
  65640. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65641. try {
  65642. _this._config = JSON.parse(xhr.response);
  65643. _this.updateShaderUniforms();
  65644. _this.updateTextures();
  65645. _this.setFragment(_this._texturePath + "/custom");
  65646. _this._animate = _this._config.animate;
  65647. _this.refreshRate = _this._config.refreshrate;
  65648. }
  65649. catch (ex) {
  65650. noConfigFile();
  65651. }
  65652. }
  65653. else {
  65654. noConfigFile();
  65655. }
  65656. }, false);
  65657. xhr.addEventListener("error", function () {
  65658. noConfigFile();
  65659. }, false);
  65660. try {
  65661. xhr.send();
  65662. }
  65663. catch (ex) {
  65664. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65665. }
  65666. };
  65667. CustomProceduralTexture.prototype.isReady = function () {
  65668. if (!_super.prototype.isReady.call(this)) {
  65669. return false;
  65670. }
  65671. for (var name in this._textures) {
  65672. var texture = this._textures[name];
  65673. if (!texture.isReady()) {
  65674. return false;
  65675. }
  65676. }
  65677. return true;
  65678. };
  65679. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65680. var scene = this.getScene();
  65681. if (this._animate && scene) {
  65682. this._time += scene.getAnimationRatio() * 0.03;
  65683. this.updateShaderUniforms();
  65684. }
  65685. _super.prototype.render.call(this, useCameraPostProcess);
  65686. };
  65687. CustomProceduralTexture.prototype.updateTextures = function () {
  65688. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65689. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65690. }
  65691. };
  65692. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65693. if (this._config) {
  65694. for (var j = 0; j < this._config.uniforms.length; j++) {
  65695. var uniform = this._config.uniforms[j];
  65696. switch (uniform.type) {
  65697. case "float":
  65698. this.setFloat(uniform.name, uniform.value);
  65699. break;
  65700. case "color3":
  65701. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65702. break;
  65703. case "color4":
  65704. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65705. break;
  65706. case "vector2":
  65707. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65708. break;
  65709. case "vector3":
  65710. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65711. break;
  65712. }
  65713. }
  65714. }
  65715. this.setFloat("time", this._time);
  65716. };
  65717. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65718. get: function () {
  65719. return this._animate;
  65720. },
  65721. set: function (value) {
  65722. this._animate = value;
  65723. },
  65724. enumerable: true,
  65725. configurable: true
  65726. });
  65727. return CustomProceduralTexture;
  65728. }(BABYLON.ProceduralTexture));
  65729. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65730. })(BABYLON || (BABYLON = {}));
  65731. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65732. "use strict";
  65733. var BABYLON;
  65734. (function (BABYLON) {
  65735. var FreeCameraGamepadInput = /** @class */ (function () {
  65736. function FreeCameraGamepadInput() {
  65737. this.gamepadAngularSensibility = 200;
  65738. this.gamepadMoveSensibility = 40;
  65739. // private members
  65740. this._cameraTransform = BABYLON.Matrix.Identity();
  65741. this._deltaTransform = BABYLON.Vector3.Zero();
  65742. this._vector3 = BABYLON.Vector3.Zero();
  65743. this._vector2 = BABYLON.Vector2.Zero();
  65744. }
  65745. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65746. var _this = this;
  65747. var manager = this.camera.getScene().gamepadManager;
  65748. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65749. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65750. // prioritize XBOX gamepads.
  65751. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65752. _this.gamepad = gamepad;
  65753. }
  65754. }
  65755. });
  65756. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65757. if (_this.gamepad === gamepad) {
  65758. _this.gamepad = null;
  65759. }
  65760. });
  65761. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65762. };
  65763. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65764. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65765. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65766. this.gamepad = null;
  65767. };
  65768. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65769. if (this.gamepad && this.gamepad.leftStick) {
  65770. var camera = this.camera;
  65771. var LSValues = this.gamepad.leftStick;
  65772. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65773. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65774. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65775. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65776. var RSValues = this.gamepad.rightStick;
  65777. if (RSValues) {
  65778. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65779. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65780. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65781. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65782. }
  65783. else {
  65784. RSValues = { x: 0, y: 0 };
  65785. }
  65786. if (!camera.rotationQuaternion) {
  65787. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65788. }
  65789. else {
  65790. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65791. }
  65792. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65793. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65794. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65795. camera.cameraDirection.addInPlace(this._deltaTransform);
  65796. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65797. camera.cameraRotation.addInPlace(this._vector2);
  65798. }
  65799. };
  65800. FreeCameraGamepadInput.prototype.getClassName = function () {
  65801. return "FreeCameraGamepadInput";
  65802. };
  65803. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65804. return "gamepad";
  65805. };
  65806. __decorate([
  65807. BABYLON.serialize()
  65808. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65809. __decorate([
  65810. BABYLON.serialize()
  65811. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65812. return FreeCameraGamepadInput;
  65813. }());
  65814. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65815. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65816. })(BABYLON || (BABYLON = {}));
  65817. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65818. "use strict";
  65819. var BABYLON;
  65820. (function (BABYLON) {
  65821. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65822. function ArcRotateCameraGamepadInput() {
  65823. this.gamepadRotationSensibility = 80;
  65824. this.gamepadMoveSensibility = 40;
  65825. }
  65826. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65827. var _this = this;
  65828. var manager = this.camera.getScene().gamepadManager;
  65829. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65830. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65831. // prioritize XBOX gamepads.
  65832. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65833. _this.gamepad = gamepad;
  65834. }
  65835. }
  65836. });
  65837. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65838. if (_this.gamepad === gamepad) {
  65839. _this.gamepad = null;
  65840. }
  65841. });
  65842. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65843. };
  65844. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65845. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65846. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65847. this.gamepad = null;
  65848. };
  65849. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65850. if (this.gamepad) {
  65851. var camera = this.camera;
  65852. var RSValues = this.gamepad.rightStick;
  65853. if (RSValues) {
  65854. if (RSValues.x != 0) {
  65855. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65856. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65857. camera.inertialAlphaOffset += normalizedRX;
  65858. }
  65859. }
  65860. if (RSValues.y != 0) {
  65861. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65862. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65863. camera.inertialBetaOffset += normalizedRY;
  65864. }
  65865. }
  65866. }
  65867. var LSValues = this.gamepad.leftStick;
  65868. if (LSValues && LSValues.y != 0) {
  65869. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65870. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65871. this.camera.inertialRadiusOffset -= normalizedLY;
  65872. }
  65873. }
  65874. }
  65875. };
  65876. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65877. return "ArcRotateCameraGamepadInput";
  65878. };
  65879. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65880. return "gamepad";
  65881. };
  65882. __decorate([
  65883. BABYLON.serialize()
  65884. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65885. __decorate([
  65886. BABYLON.serialize()
  65887. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65888. return ArcRotateCameraGamepadInput;
  65889. }());
  65890. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65891. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65892. })(BABYLON || (BABYLON = {}));
  65893. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65894. "use strict";
  65895. var BABYLON;
  65896. (function (BABYLON) {
  65897. var GamepadManager = /** @class */ (function () {
  65898. function GamepadManager(_scene) {
  65899. var _this = this;
  65900. this._scene = _scene;
  65901. this._babylonGamepads = [];
  65902. this._oneGamepadConnected = false;
  65903. this._isMonitoring = false;
  65904. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65905. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65906. this._gamepadEventSupported = false;
  65907. }
  65908. else {
  65909. this._gamepadEventSupported = 'GamepadEvent' in window;
  65910. this._gamepadSupport = (navigator.getGamepads ||
  65911. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65912. }
  65913. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65914. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65915. for (var i in _this._babylonGamepads) {
  65916. var gamepad = _this._babylonGamepads[i];
  65917. if (gamepad && gamepad._isConnected) {
  65918. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65919. }
  65920. }
  65921. });
  65922. this._onGamepadConnectedEvent = function (evt) {
  65923. var gamepad = evt.gamepad;
  65924. if (gamepad.index in _this._babylonGamepads) {
  65925. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65926. return;
  65927. }
  65928. }
  65929. var newGamepad;
  65930. if (_this._babylonGamepads[gamepad.index]) {
  65931. newGamepad = _this._babylonGamepads[gamepad.index];
  65932. newGamepad.browserGamepad = gamepad;
  65933. newGamepad._isConnected = true;
  65934. }
  65935. else {
  65936. newGamepad = _this._addNewGamepad(gamepad);
  65937. }
  65938. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65939. _this._startMonitoringGamepads();
  65940. };
  65941. this._onGamepadDisconnectedEvent = function (evt) {
  65942. var gamepad = evt.gamepad;
  65943. // Remove the gamepad from the list of gamepads to monitor.
  65944. for (var i in _this._babylonGamepads) {
  65945. if (_this._babylonGamepads[i].index === gamepad.index) {
  65946. var disconnectedGamepad = _this._babylonGamepads[i];
  65947. disconnectedGamepad._isConnected = false;
  65948. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65949. break;
  65950. }
  65951. }
  65952. };
  65953. if (this._gamepadSupport) {
  65954. //first add already-connected gamepads
  65955. this._updateGamepadObjects();
  65956. if (this._babylonGamepads.length) {
  65957. this._startMonitoringGamepads();
  65958. }
  65959. // Checking if the gamepad connected event is supported (like in Firefox)
  65960. if (this._gamepadEventSupported) {
  65961. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65962. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65963. }
  65964. else {
  65965. this._startMonitoringGamepads();
  65966. }
  65967. }
  65968. }
  65969. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65970. get: function () {
  65971. return this._babylonGamepads;
  65972. },
  65973. enumerable: true,
  65974. configurable: true
  65975. });
  65976. GamepadManager.prototype.getGamepadByType = function (type) {
  65977. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65978. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65979. var gamepad = _a[_i];
  65980. if (gamepad && gamepad.type === type) {
  65981. return gamepad;
  65982. }
  65983. }
  65984. return null;
  65985. };
  65986. GamepadManager.prototype.dispose = function () {
  65987. if (this._gamepadEventSupported) {
  65988. if (this._onGamepadConnectedEvent) {
  65989. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65990. }
  65991. if (this._onGamepadDisconnectedEvent) {
  65992. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65993. }
  65994. this._onGamepadConnectedEvent = null;
  65995. this._onGamepadDisconnectedEvent = null;
  65996. }
  65997. this._babylonGamepads.forEach(function (gamepad) {
  65998. gamepad.dispose();
  65999. });
  66000. this.onGamepadConnectedObservable.clear();
  66001. this.onGamepadDisconnectedObservable.clear();
  66002. this._oneGamepadConnected = false;
  66003. this._stopMonitoringGamepads();
  66004. this._babylonGamepads = [];
  66005. };
  66006. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  66007. if (!this._oneGamepadConnected) {
  66008. this._oneGamepadConnected = true;
  66009. }
  66010. var newGamepad;
  66011. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  66012. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  66013. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  66014. }
  66015. else if (gamepad.pose) {
  66016. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  66017. }
  66018. else {
  66019. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  66020. }
  66021. this._babylonGamepads[newGamepad.index] = newGamepad;
  66022. return newGamepad;
  66023. };
  66024. GamepadManager.prototype._startMonitoringGamepads = function () {
  66025. if (!this._isMonitoring) {
  66026. this._isMonitoring = true;
  66027. //back-comp
  66028. if (!this._scene) {
  66029. this._checkGamepadsStatus();
  66030. }
  66031. }
  66032. };
  66033. GamepadManager.prototype._stopMonitoringGamepads = function () {
  66034. this._isMonitoring = false;
  66035. };
  66036. GamepadManager.prototype._checkGamepadsStatus = function () {
  66037. var _this = this;
  66038. // Hack to be compatible Chrome
  66039. this._updateGamepadObjects();
  66040. for (var i in this._babylonGamepads) {
  66041. var gamepad = this._babylonGamepads[i];
  66042. if (!gamepad || !gamepad.isConnected) {
  66043. continue;
  66044. }
  66045. gamepad.update();
  66046. }
  66047. if (this._isMonitoring && !this._scene) {
  66048. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  66049. }
  66050. };
  66051. // This function is called only on Chrome, which does not properly support
  66052. // connection/disconnection events and forces you to recopy again the gamepad object
  66053. GamepadManager.prototype._updateGamepadObjects = function () {
  66054. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  66055. for (var i = 0; i < gamepads.length; i++) {
  66056. if (gamepads[i]) {
  66057. if (!this._babylonGamepads[gamepads[i].index]) {
  66058. var newGamepad = this._addNewGamepad(gamepads[i]);
  66059. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  66060. }
  66061. else {
  66062. // Forced to copy again this object for Chrome for unknown reason
  66063. this._babylonGamepads[i].browserGamepad = gamepads[i];
  66064. if (!this._babylonGamepads[i].isConnected) {
  66065. this._babylonGamepads[i]._isConnected = true;
  66066. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  66067. }
  66068. }
  66069. }
  66070. }
  66071. };
  66072. return GamepadManager;
  66073. }());
  66074. BABYLON.GamepadManager = GamepadManager;
  66075. })(BABYLON || (BABYLON = {}));
  66076. //# sourceMappingURL=babylon.gamepadManager.js.map
  66077. "use strict";
  66078. var BABYLON;
  66079. (function (BABYLON) {
  66080. var StickValues = /** @class */ (function () {
  66081. function StickValues(x, y) {
  66082. this.x = x;
  66083. this.y = y;
  66084. }
  66085. return StickValues;
  66086. }());
  66087. BABYLON.StickValues = StickValues;
  66088. var Gamepad = /** @class */ (function () {
  66089. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  66090. if (leftStickX === void 0) { leftStickX = 0; }
  66091. if (leftStickY === void 0) { leftStickY = 1; }
  66092. if (rightStickX === void 0) { rightStickX = 2; }
  66093. if (rightStickY === void 0) { rightStickY = 3; }
  66094. this.id = id;
  66095. this.index = index;
  66096. this.browserGamepad = browserGamepad;
  66097. this._isConnected = true;
  66098. this._invertLeftStickY = false;
  66099. this.type = Gamepad.GAMEPAD;
  66100. this._leftStickAxisX = leftStickX;
  66101. this._leftStickAxisY = leftStickY;
  66102. this._rightStickAxisX = rightStickX;
  66103. this._rightStickAxisY = rightStickY;
  66104. if (this.browserGamepad.axes.length >= 2) {
  66105. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66106. }
  66107. if (this.browserGamepad.axes.length >= 4) {
  66108. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66109. }
  66110. }
  66111. Object.defineProperty(Gamepad.prototype, "isConnected", {
  66112. get: function () {
  66113. return this._isConnected;
  66114. },
  66115. enumerable: true,
  66116. configurable: true
  66117. });
  66118. Gamepad.prototype.onleftstickchanged = function (callback) {
  66119. this._onleftstickchanged = callback;
  66120. };
  66121. Gamepad.prototype.onrightstickchanged = function (callback) {
  66122. this._onrightstickchanged = callback;
  66123. };
  66124. Object.defineProperty(Gamepad.prototype, "leftStick", {
  66125. get: function () {
  66126. return this._leftStick;
  66127. },
  66128. set: function (newValues) {
  66129. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  66130. this._onleftstickchanged(newValues);
  66131. }
  66132. this._leftStick = newValues;
  66133. },
  66134. enumerable: true,
  66135. configurable: true
  66136. });
  66137. Object.defineProperty(Gamepad.prototype, "rightStick", {
  66138. get: function () {
  66139. return this._rightStick;
  66140. },
  66141. set: function (newValues) {
  66142. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  66143. this._onrightstickchanged(newValues);
  66144. }
  66145. this._rightStick = newValues;
  66146. },
  66147. enumerable: true,
  66148. configurable: true
  66149. });
  66150. Gamepad.prototype.update = function () {
  66151. if (this._leftStick) {
  66152. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  66153. if (this._invertLeftStickY) {
  66154. this.leftStick.y *= -1;
  66155. }
  66156. }
  66157. if (this._rightStick) {
  66158. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  66159. }
  66160. };
  66161. Gamepad.prototype.dispose = function () {
  66162. };
  66163. Gamepad.GAMEPAD = 0;
  66164. Gamepad.GENERIC = 1;
  66165. Gamepad.XBOX = 2;
  66166. Gamepad.POSE_ENABLED = 3;
  66167. return Gamepad;
  66168. }());
  66169. BABYLON.Gamepad = Gamepad;
  66170. var GenericPad = /** @class */ (function (_super) {
  66171. __extends(GenericPad, _super);
  66172. function GenericPad(id, index, browserGamepad) {
  66173. var _this = _super.call(this, id, index, browserGamepad) || this;
  66174. _this.onButtonDownObservable = new BABYLON.Observable();
  66175. _this.onButtonUpObservable = new BABYLON.Observable();
  66176. _this.type = Gamepad.GENERIC;
  66177. _this._buttons = new Array(browserGamepad.buttons.length);
  66178. return _this;
  66179. }
  66180. GenericPad.prototype.onbuttondown = function (callback) {
  66181. this._onbuttondown = callback;
  66182. };
  66183. GenericPad.prototype.onbuttonup = function (callback) {
  66184. this._onbuttonup = callback;
  66185. };
  66186. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  66187. if (newValue !== currentValue) {
  66188. if (newValue === 1) {
  66189. if (this._onbuttondown) {
  66190. this._onbuttondown(buttonIndex);
  66191. }
  66192. this.onButtonDownObservable.notifyObservers(buttonIndex);
  66193. }
  66194. if (newValue === 0) {
  66195. if (this._onbuttonup) {
  66196. this._onbuttonup(buttonIndex);
  66197. }
  66198. this.onButtonUpObservable.notifyObservers(buttonIndex);
  66199. }
  66200. }
  66201. return newValue;
  66202. };
  66203. GenericPad.prototype.update = function () {
  66204. _super.prototype.update.call(this);
  66205. for (var index = 0; index < this._buttons.length; index++) {
  66206. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  66207. }
  66208. };
  66209. GenericPad.prototype.dispose = function () {
  66210. _super.prototype.dispose.call(this);
  66211. this.onButtonDownObservable.clear();
  66212. this.onButtonUpObservable.clear();
  66213. };
  66214. return GenericPad;
  66215. }(Gamepad));
  66216. BABYLON.GenericPad = GenericPad;
  66217. })(BABYLON || (BABYLON = {}));
  66218. //# sourceMappingURL=babylon.gamepad.js.map
  66219. "use strict";
  66220. var BABYLON;
  66221. (function (BABYLON) {
  66222. var Xbox360Button;
  66223. (function (Xbox360Button) {
  66224. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  66225. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  66226. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  66227. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  66228. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  66229. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  66230. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  66231. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  66232. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  66233. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  66234. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  66235. var Xbox360Dpad;
  66236. (function (Xbox360Dpad) {
  66237. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  66238. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  66239. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  66240. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  66241. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  66242. var Xbox360Pad = /** @class */ (function (_super) {
  66243. __extends(Xbox360Pad, _super);
  66244. function Xbox360Pad(id, index, gamepad, xboxOne) {
  66245. if (xboxOne === void 0) { xboxOne = false; }
  66246. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  66247. _this._leftTrigger = 0;
  66248. _this._rightTrigger = 0;
  66249. _this.onButtonDownObservable = new BABYLON.Observable();
  66250. _this.onButtonUpObservable = new BABYLON.Observable();
  66251. _this.onPadDownObservable = new BABYLON.Observable();
  66252. _this.onPadUpObservable = new BABYLON.Observable();
  66253. _this._buttonA = 0;
  66254. _this._buttonB = 0;
  66255. _this._buttonX = 0;
  66256. _this._buttonY = 0;
  66257. _this._buttonBack = 0;
  66258. _this._buttonStart = 0;
  66259. _this._buttonLB = 0;
  66260. _this._buttonRB = 0;
  66261. _this._buttonLeftStick = 0;
  66262. _this._buttonRightStick = 0;
  66263. _this._dPadUp = 0;
  66264. _this._dPadDown = 0;
  66265. _this._dPadLeft = 0;
  66266. _this._dPadRight = 0;
  66267. _this._isXboxOnePad = false;
  66268. _this.type = BABYLON.Gamepad.XBOX;
  66269. _this._isXboxOnePad = xboxOne;
  66270. return _this;
  66271. }
  66272. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  66273. this._onlefttriggerchanged = callback;
  66274. };
  66275. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  66276. this._onrighttriggerchanged = callback;
  66277. };
  66278. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  66279. get: function () {
  66280. return this._leftTrigger;
  66281. },
  66282. set: function (newValue) {
  66283. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  66284. this._onlefttriggerchanged(newValue);
  66285. }
  66286. this._leftTrigger = newValue;
  66287. },
  66288. enumerable: true,
  66289. configurable: true
  66290. });
  66291. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  66292. get: function () {
  66293. return this._rightTrigger;
  66294. },
  66295. set: function (newValue) {
  66296. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  66297. this._onrighttriggerchanged(newValue);
  66298. }
  66299. this._rightTrigger = newValue;
  66300. },
  66301. enumerable: true,
  66302. configurable: true
  66303. });
  66304. Xbox360Pad.prototype.onbuttondown = function (callback) {
  66305. this._onbuttondown = callback;
  66306. };
  66307. Xbox360Pad.prototype.onbuttonup = function (callback) {
  66308. this._onbuttonup = callback;
  66309. };
  66310. Xbox360Pad.prototype.ondpaddown = function (callback) {
  66311. this._ondpaddown = callback;
  66312. };
  66313. Xbox360Pad.prototype.ondpadup = function (callback) {
  66314. this._ondpadup = callback;
  66315. };
  66316. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66317. if (newValue !== currentValue) {
  66318. if (newValue === 1) {
  66319. if (this._onbuttondown) {
  66320. this._onbuttondown(buttonType);
  66321. }
  66322. this.onButtonDownObservable.notifyObservers(buttonType);
  66323. }
  66324. if (newValue === 0) {
  66325. if (this._onbuttonup) {
  66326. this._onbuttonup(buttonType);
  66327. }
  66328. this.onButtonUpObservable.notifyObservers(buttonType);
  66329. }
  66330. }
  66331. return newValue;
  66332. };
  66333. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66334. if (newValue !== currentValue) {
  66335. if (newValue === 1) {
  66336. if (this._ondpaddown) {
  66337. this._ondpaddown(buttonType);
  66338. }
  66339. this.onPadDownObservable.notifyObservers(buttonType);
  66340. }
  66341. if (newValue === 0) {
  66342. if (this._ondpadup) {
  66343. this._ondpadup(buttonType);
  66344. }
  66345. this.onPadUpObservable.notifyObservers(buttonType);
  66346. }
  66347. }
  66348. return newValue;
  66349. };
  66350. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66351. get: function () {
  66352. return this._buttonA;
  66353. },
  66354. set: function (value) {
  66355. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66356. },
  66357. enumerable: true,
  66358. configurable: true
  66359. });
  66360. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66361. get: function () {
  66362. return this._buttonB;
  66363. },
  66364. set: function (value) {
  66365. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66366. },
  66367. enumerable: true,
  66368. configurable: true
  66369. });
  66370. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66371. get: function () {
  66372. return this._buttonX;
  66373. },
  66374. set: function (value) {
  66375. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66376. },
  66377. enumerable: true,
  66378. configurable: true
  66379. });
  66380. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66381. get: function () {
  66382. return this._buttonY;
  66383. },
  66384. set: function (value) {
  66385. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66386. },
  66387. enumerable: true,
  66388. configurable: true
  66389. });
  66390. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66391. get: function () {
  66392. return this._buttonStart;
  66393. },
  66394. set: function (value) {
  66395. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66396. },
  66397. enumerable: true,
  66398. configurable: true
  66399. });
  66400. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66401. get: function () {
  66402. return this._buttonBack;
  66403. },
  66404. set: function (value) {
  66405. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66406. },
  66407. enumerable: true,
  66408. configurable: true
  66409. });
  66410. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66411. get: function () {
  66412. return this._buttonLB;
  66413. },
  66414. set: function (value) {
  66415. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66416. },
  66417. enumerable: true,
  66418. configurable: true
  66419. });
  66420. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66421. get: function () {
  66422. return this._buttonRB;
  66423. },
  66424. set: function (value) {
  66425. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66426. },
  66427. enumerable: true,
  66428. configurable: true
  66429. });
  66430. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66431. get: function () {
  66432. return this._buttonLeftStick;
  66433. },
  66434. set: function (value) {
  66435. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66436. },
  66437. enumerable: true,
  66438. configurable: true
  66439. });
  66440. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66441. get: function () {
  66442. return this._buttonRightStick;
  66443. },
  66444. set: function (value) {
  66445. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66446. },
  66447. enumerable: true,
  66448. configurable: true
  66449. });
  66450. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66451. get: function () {
  66452. return this._dPadUp;
  66453. },
  66454. set: function (value) {
  66455. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66456. },
  66457. enumerable: true,
  66458. configurable: true
  66459. });
  66460. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66461. get: function () {
  66462. return this._dPadDown;
  66463. },
  66464. set: function (value) {
  66465. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66466. },
  66467. enumerable: true,
  66468. configurable: true
  66469. });
  66470. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66471. get: function () {
  66472. return this._dPadLeft;
  66473. },
  66474. set: function (value) {
  66475. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66476. },
  66477. enumerable: true,
  66478. configurable: true
  66479. });
  66480. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66481. get: function () {
  66482. return this._dPadRight;
  66483. },
  66484. set: function (value) {
  66485. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66486. },
  66487. enumerable: true,
  66488. configurable: true
  66489. });
  66490. Xbox360Pad.prototype.update = function () {
  66491. _super.prototype.update.call(this);
  66492. if (this._isXboxOnePad) {
  66493. this.buttonA = this.browserGamepad.buttons[0].value;
  66494. this.buttonB = this.browserGamepad.buttons[1].value;
  66495. this.buttonX = this.browserGamepad.buttons[2].value;
  66496. this.buttonY = this.browserGamepad.buttons[3].value;
  66497. this.buttonLB = this.browserGamepad.buttons[4].value;
  66498. this.buttonRB = this.browserGamepad.buttons[5].value;
  66499. this.leftTrigger = this.browserGamepad.axes[2];
  66500. this.rightTrigger = this.browserGamepad.axes[5];
  66501. this.buttonBack = this.browserGamepad.buttons[9].value;
  66502. this.buttonStart = this.browserGamepad.buttons[8].value;
  66503. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66504. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66505. this.dPadUp = this.browserGamepad.buttons[11].value;
  66506. this.dPadDown = this.browserGamepad.buttons[12].value;
  66507. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66508. this.dPadRight = this.browserGamepad.buttons[14].value;
  66509. }
  66510. else {
  66511. this.buttonA = this.browserGamepad.buttons[0].value;
  66512. this.buttonB = this.browserGamepad.buttons[1].value;
  66513. this.buttonX = this.browserGamepad.buttons[2].value;
  66514. this.buttonY = this.browserGamepad.buttons[3].value;
  66515. this.buttonLB = this.browserGamepad.buttons[4].value;
  66516. this.buttonRB = this.browserGamepad.buttons[5].value;
  66517. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66518. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66519. this.buttonBack = this.browserGamepad.buttons[8].value;
  66520. this.buttonStart = this.browserGamepad.buttons[9].value;
  66521. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66522. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66523. this.dPadUp = this.browserGamepad.buttons[12].value;
  66524. this.dPadDown = this.browserGamepad.buttons[13].value;
  66525. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66526. this.dPadRight = this.browserGamepad.buttons[15].value;
  66527. }
  66528. };
  66529. Xbox360Pad.prototype.dispose = function () {
  66530. _super.prototype.dispose.call(this);
  66531. this.onButtonDownObservable.clear();
  66532. this.onButtonUpObservable.clear();
  66533. this.onPadDownObservable.clear();
  66534. this.onPadUpObservable.clear();
  66535. };
  66536. return Xbox360Pad;
  66537. }(BABYLON.Gamepad));
  66538. BABYLON.Xbox360Pad = Xbox360Pad;
  66539. })(BABYLON || (BABYLON = {}));
  66540. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66541. "use strict";
  66542. var BABYLON;
  66543. (function (BABYLON) {
  66544. var PoseEnabledControllerType;
  66545. (function (PoseEnabledControllerType) {
  66546. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66547. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66548. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66549. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66550. /**
  66551. * Google Daydream
  66552. */
  66553. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66554. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66555. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66556. var PoseEnabledControllerHelper = /** @class */ (function () {
  66557. function PoseEnabledControllerHelper() {
  66558. }
  66559. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66560. // Oculus Touch
  66561. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66562. return new BABYLON.OculusTouchController(vrGamepad);
  66563. }
  66564. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66565. return new BABYLON.WindowsMotionController(vrGamepad);
  66566. }
  66567. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66568. return new BABYLON.ViveController(vrGamepad);
  66569. }
  66570. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66571. return new BABYLON.GearVRController(vrGamepad);
  66572. }
  66573. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66574. return new BABYLON.DaydreamController(vrGamepad);
  66575. }
  66576. else {
  66577. return new BABYLON.GenericController(vrGamepad);
  66578. }
  66579. };
  66580. return PoseEnabledControllerHelper;
  66581. }());
  66582. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66583. var PoseEnabledController = /** @class */ (function (_super) {
  66584. __extends(PoseEnabledController, _super);
  66585. function PoseEnabledController(browserGamepad) {
  66586. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66587. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66588. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66589. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66590. // Represents device position and rotation in babylon space
  66591. _this.devicePosition = BABYLON.Vector3.Zero();
  66592. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66593. _this.deviceScaleFactor = 1;
  66594. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66595. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66596. /**
  66597. * Node to be used when casting a ray from the controller
  66598. */
  66599. _this._pointingPoseNode = null;
  66600. _this._workingMatrix = BABYLON.Matrix.Identity();
  66601. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66602. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66603. _this.position = BABYLON.Vector3.Zero();
  66604. _this.rotationQuaternion = new BABYLON.Quaternion();
  66605. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66606. _this._calculatedRotation = new BABYLON.Quaternion();
  66607. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66608. return _this;
  66609. }
  66610. PoseEnabledController.prototype.update = function () {
  66611. _super.prototype.update.call(this);
  66612. var pose = this.browserGamepad.pose;
  66613. this.updateFromDevice(pose);
  66614. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66615. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66616. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66617. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66618. if (this._mesh) {
  66619. this._mesh.position.copyFrom(this.devicePosition);
  66620. if (this._mesh.rotationQuaternion) {
  66621. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66622. }
  66623. }
  66624. };
  66625. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66626. if (poseData) {
  66627. this.rawPose = poseData;
  66628. if (poseData.position) {
  66629. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66630. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66631. this._deviceRoomPosition.z *= -1;
  66632. }
  66633. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66634. this._calculatedPosition.addInPlace(this.position);
  66635. }
  66636. var pose = this.rawPose;
  66637. if (poseData.orientation && pose.orientation) {
  66638. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66639. if (this._mesh) {
  66640. if (this._mesh.getScene().useRightHandedSystem) {
  66641. this._deviceRoomRotationQuaternion.z *= -1;
  66642. this._deviceRoomRotationQuaternion.w *= -1;
  66643. }
  66644. else {
  66645. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66646. }
  66647. }
  66648. // if the camera is set, rotate to the camera's rotation
  66649. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66650. }
  66651. }
  66652. };
  66653. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66654. if (this._mesh) {
  66655. this._mesh.parent = null;
  66656. }
  66657. this._mesh = mesh;
  66658. if (this._poseControlledCamera) {
  66659. this._mesh.parent = this._poseControlledCamera;
  66660. }
  66661. if (!this._mesh.rotationQuaternion) {
  66662. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66663. }
  66664. };
  66665. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66666. this._poseControlledCamera = camera;
  66667. if (this._mesh) {
  66668. this._mesh.parent = this._poseControlledCamera;
  66669. }
  66670. };
  66671. PoseEnabledController.prototype.dispose = function () {
  66672. if (this._mesh) {
  66673. this._mesh.dispose();
  66674. }
  66675. this._mesh = null;
  66676. _super.prototype.dispose.call(this);
  66677. };
  66678. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66679. get: function () {
  66680. return this._mesh;
  66681. },
  66682. enumerable: true,
  66683. configurable: true
  66684. });
  66685. PoseEnabledController.prototype.getForwardRay = function (length) {
  66686. if (length === void 0) { length = 100; }
  66687. if (!this.mesh) {
  66688. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66689. }
  66690. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66691. var origin = m.getTranslation();
  66692. var forward = new BABYLON.Vector3(0, 0, -1);
  66693. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66694. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66695. return new BABYLON.Ray(origin, direction, length);
  66696. };
  66697. /**
  66698. * Name of the child mesh that can be used to cast a ray from the controller
  66699. */
  66700. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66701. return PoseEnabledController;
  66702. }(BABYLON.Gamepad));
  66703. BABYLON.PoseEnabledController = PoseEnabledController;
  66704. })(BABYLON || (BABYLON = {}));
  66705. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66706. "use strict";
  66707. var BABYLON;
  66708. (function (BABYLON) {
  66709. var WebVRController = /** @class */ (function (_super) {
  66710. __extends(WebVRController, _super);
  66711. function WebVRController(vrGamepad) {
  66712. var _this = _super.call(this, vrGamepad) || this;
  66713. // Observables
  66714. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66715. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66716. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66717. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66718. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66719. _this.pad = { x: 0, y: 0 };
  66720. // avoid GC, store state in a tmp object
  66721. _this._changes = {
  66722. pressChanged: false,
  66723. touchChanged: false,
  66724. valueChanged: false,
  66725. changed: false
  66726. };
  66727. _this._buttons = new Array(vrGamepad.buttons.length);
  66728. _this.hand = vrGamepad.hand;
  66729. return _this;
  66730. }
  66731. WebVRController.prototype.onButtonStateChange = function (callback) {
  66732. this._onButtonStateChange = callback;
  66733. };
  66734. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66735. get: function () {
  66736. return this._defaultModel;
  66737. },
  66738. enumerable: true,
  66739. configurable: true
  66740. });
  66741. WebVRController.prototype.update = function () {
  66742. _super.prototype.update.call(this);
  66743. for (var index = 0; index < this._buttons.length; index++) {
  66744. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66745. }
  66746. ;
  66747. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66748. this.pad.x = this.leftStick.x;
  66749. this.pad.y = this.leftStick.y;
  66750. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66751. }
  66752. };
  66753. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66754. if (!newState) {
  66755. newState = {
  66756. pressed: false,
  66757. touched: false,
  66758. value: 0
  66759. };
  66760. }
  66761. if (!currentState) {
  66762. this._buttons[buttonIndex] = {
  66763. pressed: newState.pressed,
  66764. touched: newState.touched,
  66765. value: newState.value
  66766. };
  66767. return;
  66768. }
  66769. this._checkChanges(newState, currentState);
  66770. if (this._changes.changed) {
  66771. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66772. this._handleButtonChange(buttonIndex, newState, this._changes);
  66773. }
  66774. this._buttons[buttonIndex].pressed = newState.pressed;
  66775. this._buttons[buttonIndex].touched = newState.touched;
  66776. // oculus triggers are never 0, thou not touched.
  66777. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66778. };
  66779. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66780. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66781. this._changes.touchChanged = newState.touched !== currentState.touched;
  66782. this._changes.valueChanged = newState.value !== currentState.value;
  66783. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66784. return this._changes;
  66785. };
  66786. WebVRController.prototype.dispose = function () {
  66787. _super.prototype.dispose.call(this);
  66788. this.onTriggerStateChangedObservable.clear();
  66789. this.onMainButtonStateChangedObservable.clear();
  66790. this.onSecondaryButtonStateChangedObservable.clear();
  66791. this.onPadStateChangedObservable.clear();
  66792. this.onPadValuesChangedObservable.clear();
  66793. };
  66794. return WebVRController;
  66795. }(BABYLON.PoseEnabledController));
  66796. BABYLON.WebVRController = WebVRController;
  66797. })(BABYLON || (BABYLON = {}));
  66798. //# sourceMappingURL=babylon.webVRController.js.map
  66799. "use strict";
  66800. var BABYLON;
  66801. (function (BABYLON) {
  66802. var OculusTouchController = /** @class */ (function (_super) {
  66803. __extends(OculusTouchController, _super);
  66804. function OculusTouchController(vrGamepad) {
  66805. var _this = _super.call(this, vrGamepad) || this;
  66806. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66807. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66808. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66809. return _this;
  66810. }
  66811. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66812. var _this = this;
  66813. var meshName;
  66814. // Hand
  66815. if (this.hand === 'left') {
  66816. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66817. }
  66818. else {
  66819. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66820. }
  66821. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66822. /*
  66823. Parent Mesh name: oculus_touch_left
  66824. - body
  66825. - trigger
  66826. - thumbstick
  66827. - grip
  66828. - button_y
  66829. - button_x
  66830. - button_enter
  66831. */
  66832. _this._defaultModel = newMeshes[1];
  66833. _this.attachToMesh(_this._defaultModel);
  66834. if (meshLoaded) {
  66835. meshLoaded(_this._defaultModel);
  66836. }
  66837. });
  66838. };
  66839. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66840. // helper getters for left and right hand.
  66841. get: function () {
  66842. if (this.hand === 'right') {
  66843. return this.onMainButtonStateChangedObservable;
  66844. }
  66845. else {
  66846. throw new Error('No A button on left hand');
  66847. }
  66848. },
  66849. enumerable: true,
  66850. configurable: true
  66851. });
  66852. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66853. get: function () {
  66854. if (this.hand === 'right') {
  66855. return this.onSecondaryButtonStateChangedObservable;
  66856. }
  66857. else {
  66858. throw new Error('No B button on left hand');
  66859. }
  66860. },
  66861. enumerable: true,
  66862. configurable: true
  66863. });
  66864. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66865. get: function () {
  66866. if (this.hand === 'left') {
  66867. return this.onMainButtonStateChangedObservable;
  66868. }
  66869. else {
  66870. throw new Error('No X button on right hand');
  66871. }
  66872. },
  66873. enumerable: true,
  66874. configurable: true
  66875. });
  66876. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66877. get: function () {
  66878. if (this.hand === 'left') {
  66879. return this.onSecondaryButtonStateChangedObservable;
  66880. }
  66881. else {
  66882. throw new Error('No Y button on right hand');
  66883. }
  66884. },
  66885. enumerable: true,
  66886. configurable: true
  66887. });
  66888. /*
  66889. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66890. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66891. 2) secondary trigger (same)
  66892. 3) A (right) X (left), touch, pressed = value
  66893. 4) B / Y
  66894. 5) thumb rest
  66895. */
  66896. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66897. var notifyObject = state; //{ state: state, changes: changes };
  66898. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66899. switch (buttonIdx) {
  66900. case 0:
  66901. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66902. return;
  66903. case 1:// index trigger
  66904. if (this._defaultModel) {
  66905. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66906. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66907. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66908. }
  66909. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66910. return;
  66911. case 2:// secondary trigger
  66912. if (this._defaultModel) {
  66913. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66914. }
  66915. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66916. return;
  66917. case 3:
  66918. if (this._defaultModel) {
  66919. if (notifyObject.pressed) {
  66920. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66921. }
  66922. else {
  66923. (this._defaultModel.getChildren()[1]).position.y = 0;
  66924. }
  66925. }
  66926. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66927. return;
  66928. case 4:
  66929. if (this._defaultModel) {
  66930. if (notifyObject.pressed) {
  66931. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66932. }
  66933. else {
  66934. (this._defaultModel.getChildren()[2]).position.y = 0;
  66935. }
  66936. }
  66937. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66938. return;
  66939. case 5:
  66940. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66941. return;
  66942. }
  66943. };
  66944. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66945. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66946. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66947. return OculusTouchController;
  66948. }(BABYLON.WebVRController));
  66949. BABYLON.OculusTouchController = OculusTouchController;
  66950. })(BABYLON || (BABYLON = {}));
  66951. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66952. "use strict";
  66953. var BABYLON;
  66954. (function (BABYLON) {
  66955. var ViveController = /** @class */ (function (_super) {
  66956. __extends(ViveController, _super);
  66957. function ViveController(vrGamepad) {
  66958. var _this = _super.call(this, vrGamepad) || this;
  66959. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66960. _this._invertLeftStickY = true;
  66961. return _this;
  66962. }
  66963. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66964. var _this = this;
  66965. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66966. /*
  66967. Parent Mesh name: ViveWand
  66968. - body
  66969. - r_gripper
  66970. - l_gripper
  66971. - menu_button
  66972. - system_button
  66973. - trackpad
  66974. - trigger
  66975. - LED
  66976. */
  66977. _this._defaultModel = newMeshes[1];
  66978. _this.attachToMesh(_this._defaultModel);
  66979. if (meshLoaded) {
  66980. meshLoaded(_this._defaultModel);
  66981. }
  66982. });
  66983. };
  66984. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66985. get: function () {
  66986. return this.onMainButtonStateChangedObservable;
  66987. },
  66988. enumerable: true,
  66989. configurable: true
  66990. });
  66991. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66992. get: function () {
  66993. return this.onMainButtonStateChangedObservable;
  66994. },
  66995. enumerable: true,
  66996. configurable: true
  66997. });
  66998. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66999. get: function () {
  67000. return this.onSecondaryButtonStateChangedObservable;
  67001. },
  67002. enumerable: true,
  67003. configurable: true
  67004. });
  67005. /**
  67006. * Vive mapping:
  67007. * 0: touchpad
  67008. * 1: trigger
  67009. * 2: left AND right buttons
  67010. * 3: menu button
  67011. */
  67012. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67013. var notifyObject = state; //{ state: state, changes: changes };
  67014. switch (buttonIdx) {
  67015. case 0:
  67016. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  67017. return;
  67018. case 1:// index trigger
  67019. if (this._defaultModel) {
  67020. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  67021. }
  67022. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  67023. return;
  67024. case 2:// left AND right button
  67025. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  67026. return;
  67027. case 3:
  67028. if (this._defaultModel) {
  67029. if (notifyObject.pressed) {
  67030. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  67031. }
  67032. else {
  67033. (this._defaultModel.getChildren()[2]).position.y = 0;
  67034. }
  67035. }
  67036. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  67037. return;
  67038. }
  67039. };
  67040. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  67041. ViveController.MODEL_FILENAME = 'wand.babylon';
  67042. return ViveController;
  67043. }(BABYLON.WebVRController));
  67044. BABYLON.ViveController = ViveController;
  67045. })(BABYLON || (BABYLON = {}));
  67046. //# sourceMappingURL=babylon.viveController.js.map
  67047. "use strict";
  67048. var BABYLON;
  67049. (function (BABYLON) {
  67050. var GenericController = /** @class */ (function (_super) {
  67051. __extends(GenericController, _super);
  67052. function GenericController(vrGamepad) {
  67053. return _super.call(this, vrGamepad) || this;
  67054. }
  67055. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67056. var _this = this;
  67057. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  67058. _this._defaultModel = newMeshes[1];
  67059. _this.attachToMesh(_this._defaultModel);
  67060. if (meshLoaded) {
  67061. meshLoaded(_this._defaultModel);
  67062. }
  67063. });
  67064. };
  67065. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67066. console.log("Button id: " + buttonIdx + "state: ");
  67067. console.dir(state);
  67068. };
  67069. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67070. GenericController.MODEL_FILENAME = 'generic.babylon';
  67071. return GenericController;
  67072. }(BABYLON.WebVRController));
  67073. BABYLON.GenericController = GenericController;
  67074. })(BABYLON || (BABYLON = {}));
  67075. //# sourceMappingURL=babylon.genericController.js.map
  67076. "use strict";
  67077. var BABYLON;
  67078. (function (BABYLON) {
  67079. var LoadedMeshInfo = /** @class */ (function () {
  67080. function LoadedMeshInfo() {
  67081. this.buttonMeshes = {};
  67082. this.axisMeshes = {};
  67083. }
  67084. return LoadedMeshInfo;
  67085. }());
  67086. var WindowsMotionController = /** @class */ (function (_super) {
  67087. __extends(WindowsMotionController, _super);
  67088. function WindowsMotionController(vrGamepad) {
  67089. var _this = _super.call(this, vrGamepad) || this;
  67090. _this._mapping = {
  67091. // Semantic button names
  67092. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  67093. // A mapping of the button name to glTF model node name
  67094. // that should be transformed by button value.
  67095. buttonMeshNames: {
  67096. 'trigger': 'SELECT',
  67097. 'menu': 'MENU',
  67098. 'grip': 'GRASP',
  67099. 'thumbstick': 'THUMBSTICK_PRESS',
  67100. 'trackpad': 'TOUCHPAD_PRESS'
  67101. },
  67102. // This mapping is used to translate from the Motion Controller to Babylon semantics
  67103. buttonObservableNames: {
  67104. 'trigger': 'onTriggerStateChangedObservable',
  67105. 'menu': 'onSecondaryButtonStateChangedObservable',
  67106. 'grip': 'onMainButtonStateChangedObservable',
  67107. 'thumbstick': 'onPadStateChangedObservable',
  67108. 'trackpad': 'onTrackpadChangedObservable'
  67109. },
  67110. // A mapping of the axis name to glTF model node name
  67111. // that should be transformed by axis value.
  67112. // This array mirrors the browserGamepad.axes array, such that
  67113. // the mesh corresponding to axis 0 is in this array index 0.
  67114. axisMeshNames: [
  67115. 'THUMBSTICK_X',
  67116. 'THUMBSTICK_Y',
  67117. 'TOUCHPAD_TOUCH_X',
  67118. 'TOUCHPAD_TOUCH_Y'
  67119. ],
  67120. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  67121. };
  67122. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  67123. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  67124. _this.trackpad = { x: 0, y: 0 };
  67125. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  67126. _this._loadedMeshInfo = null;
  67127. return _this;
  67128. }
  67129. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  67130. get: function () {
  67131. return this.onTriggerStateChangedObservable;
  67132. },
  67133. enumerable: true,
  67134. configurable: true
  67135. });
  67136. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  67137. get: function () {
  67138. return this.onSecondaryButtonStateChangedObservable;
  67139. },
  67140. enumerable: true,
  67141. configurable: true
  67142. });
  67143. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  67144. get: function () {
  67145. return this.onMainButtonStateChangedObservable;
  67146. },
  67147. enumerable: true,
  67148. configurable: true
  67149. });
  67150. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  67151. get: function () {
  67152. return this.onPadStateChangedObservable;
  67153. },
  67154. enumerable: true,
  67155. configurable: true
  67156. });
  67157. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  67158. get: function () {
  67159. return this.onTrackpadChangedObservable;
  67160. },
  67161. enumerable: true,
  67162. configurable: true
  67163. });
  67164. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  67165. get: function () {
  67166. return this.onTrackpadValuesChangedObservable;
  67167. },
  67168. enumerable: true,
  67169. configurable: true
  67170. });
  67171. /**
  67172. * Called once per frame by the engine.
  67173. */
  67174. WindowsMotionController.prototype.update = function () {
  67175. _super.prototype.update.call(this);
  67176. if (this.browserGamepad.axes) {
  67177. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  67178. this.trackpad.x = this.browserGamepad["axes"][2];
  67179. this.trackpad.y = this.browserGamepad["axes"][3];
  67180. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  67181. }
  67182. // Only need to animate axes if there is a loaded mesh
  67183. if (this._loadedMeshInfo) {
  67184. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  67185. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  67186. }
  67187. }
  67188. }
  67189. };
  67190. /**
  67191. * Called once for each button that changed state since the last frame
  67192. * @param buttonIdx Which button index changed
  67193. * @param state New state of the button
  67194. * @param changes Which properties on the state changed since last frame
  67195. */
  67196. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67197. var buttonName = this._mapping.buttons[buttonIdx];
  67198. if (!buttonName) {
  67199. return;
  67200. }
  67201. // Only emit events for buttons that we know how to map from index to name
  67202. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  67203. if (observable) {
  67204. observable.notifyObservers(state);
  67205. }
  67206. this.lerpButtonTransform(buttonName, state.value);
  67207. };
  67208. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  67209. // If there is no loaded mesh, there is nothing to transform.
  67210. if (!this._loadedMeshInfo) {
  67211. return;
  67212. }
  67213. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  67214. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67215. return;
  67216. }
  67217. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  67218. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  67219. };
  67220. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  67221. if (!this._loadedMeshInfo) {
  67222. return;
  67223. }
  67224. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  67225. if (!meshInfo) {
  67226. return;
  67227. }
  67228. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  67229. return;
  67230. }
  67231. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  67232. var lerpValue = axisValue * 0.5 + 0.5;
  67233. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  67234. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  67235. };
  67236. /**
  67237. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  67238. * @param scene scene in which to add meshes
  67239. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  67240. */
  67241. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  67242. var _this = this;
  67243. if (forceDefault === void 0) { forceDefault = false; }
  67244. var path;
  67245. var filename;
  67246. // Checking if GLB loader is present
  67247. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  67248. // Determine the device specific folder based on the ID suffix
  67249. var device = 'default';
  67250. if (this.id && !forceDefault) {
  67251. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  67252. device = ((match && match[0]) || device);
  67253. }
  67254. // Hand
  67255. if (this.hand === 'left') {
  67256. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  67257. }
  67258. else {
  67259. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  67260. }
  67261. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  67262. }
  67263. else {
  67264. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  67265. path = BABYLON.GenericController.MODEL_BASE_URL;
  67266. filename = BABYLON.GenericController.MODEL_FILENAME;
  67267. }
  67268. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  67269. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  67270. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  67271. if (!_this._loadedMeshInfo) {
  67272. return;
  67273. }
  67274. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  67275. _this.attachToMesh(_this._defaultModel);
  67276. if (meshLoaded) {
  67277. meshLoaded(_this._defaultModel);
  67278. }
  67279. }, null, function (scene, message) {
  67280. BABYLON.Tools.Log(message);
  67281. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  67282. if (!forceDefault) {
  67283. _this.initControllerMesh(scene, meshLoaded, true);
  67284. }
  67285. });
  67286. };
  67287. /**
  67288. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  67289. * can be transformed by button presses and axes values, based on this._mapping.
  67290. *
  67291. * @param scene scene in which the meshes exist
  67292. * @param meshes list of meshes that make up the controller model to process
  67293. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  67294. */
  67295. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  67296. var loadedMeshInfo = null;
  67297. // Create a new mesh to contain the glTF hierarchy
  67298. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  67299. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  67300. var childMesh = null;
  67301. for (var i = 0; i < meshes.length; i++) {
  67302. var mesh = meshes[i];
  67303. if (!mesh.parent) {
  67304. // Exclude controller meshes from picking results
  67305. mesh.isPickable = false;
  67306. // Handle root node, attach to the new parentMesh
  67307. childMesh = mesh;
  67308. break;
  67309. }
  67310. }
  67311. if (childMesh) {
  67312. childMesh.setParent(parentMesh);
  67313. // Create our mesh info. Note that this method will always return non-null.
  67314. loadedMeshInfo = this.createMeshInfo(parentMesh);
  67315. }
  67316. else {
  67317. BABYLON.Tools.Warn('Could not find root node in model file.');
  67318. }
  67319. return loadedMeshInfo;
  67320. };
  67321. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67322. var loadedMeshInfo = new LoadedMeshInfo();
  67323. var i;
  67324. loadedMeshInfo.rootNode = rootNode;
  67325. // Reset the caches
  67326. loadedMeshInfo.buttonMeshes = {};
  67327. loadedMeshInfo.axisMeshes = {};
  67328. // Button Meshes
  67329. for (i = 0; i < this._mapping.buttons.length; i++) {
  67330. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67331. if (!buttonMeshName) {
  67332. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67333. continue;
  67334. }
  67335. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67336. if (!buttonMesh) {
  67337. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67338. continue;
  67339. }
  67340. var buttonMeshInfo = {
  67341. index: i,
  67342. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67343. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67344. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67345. };
  67346. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67347. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67348. }
  67349. else {
  67350. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67351. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67352. '(VALUE: ' + !!buttonMeshInfo.value +
  67353. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67354. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67355. ')');
  67356. }
  67357. }
  67358. // Axis Meshes
  67359. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67360. var axisMeshName = this._mapping.axisMeshNames[i];
  67361. if (!axisMeshName) {
  67362. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67363. continue;
  67364. }
  67365. var axisMesh = getChildByName(rootNode, axisMeshName);
  67366. if (!axisMesh) {
  67367. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67368. continue;
  67369. }
  67370. var axisMeshInfo = {
  67371. index: i,
  67372. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67373. min: getImmediateChildByName(axisMesh, 'MIN'),
  67374. max: getImmediateChildByName(axisMesh, 'MAX')
  67375. };
  67376. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67377. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67378. }
  67379. else {
  67380. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67381. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67382. '(VALUE: ' + !!axisMeshInfo.value +
  67383. ', MIN: ' + !!axisMeshInfo.min +
  67384. ', MAX:' + !!axisMeshInfo.max +
  67385. ')');
  67386. }
  67387. }
  67388. // Pointing Ray
  67389. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67390. if (!loadedMeshInfo.pointingPoseNode) {
  67391. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67392. }
  67393. return loadedMeshInfo;
  67394. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67395. function getChildByName(node, name) {
  67396. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67397. }
  67398. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67399. function getImmediateChildByName(node, name) {
  67400. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67401. }
  67402. };
  67403. WindowsMotionController.prototype.getForwardRay = function (length) {
  67404. if (length === void 0) { length = 100; }
  67405. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67406. return _super.prototype.getForwardRay.call(this, length);
  67407. }
  67408. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67409. var origin = m.getTranslation();
  67410. var forward = new BABYLON.Vector3(0, 0, -1);
  67411. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67412. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67413. return new BABYLON.Ray(origin, direction, length);
  67414. };
  67415. WindowsMotionController.prototype.dispose = function () {
  67416. _super.prototype.dispose.call(this);
  67417. this.onTrackpadChangedObservable.clear();
  67418. };
  67419. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67420. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67421. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67422. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67423. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67424. return WindowsMotionController;
  67425. }(BABYLON.WebVRController));
  67426. BABYLON.WindowsMotionController = WindowsMotionController;
  67427. })(BABYLON || (BABYLON = {}));
  67428. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67429. "use strict";
  67430. var BABYLON;
  67431. (function (BABYLON) {
  67432. var GearVRController = /** @class */ (function (_super) {
  67433. __extends(GearVRController, _super);
  67434. function GearVRController(vrGamepad) {
  67435. var _this = _super.call(this, vrGamepad) || this;
  67436. _this._buttonIndexToObservableNameMap = [
  67437. 'onTrackpadChangedObservable',
  67438. 'onTriggerStateChangedObservable' // Trigger
  67439. ];
  67440. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67441. return _this;
  67442. }
  67443. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67444. var _this = this;
  67445. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67446. _this._defaultModel = newMeshes[1];
  67447. _this.attachToMesh(_this._defaultModel);
  67448. if (meshLoaded) {
  67449. meshLoaded(_this._defaultModel);
  67450. }
  67451. });
  67452. };
  67453. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67454. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67455. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67456. // Only emit events for buttons that we know how to map from index to observable
  67457. var observable = this[observableName];
  67458. if (observable) {
  67459. observable.notifyObservers(state);
  67460. }
  67461. }
  67462. };
  67463. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67464. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67465. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67466. return GearVRController;
  67467. }(BABYLON.WebVRController));
  67468. BABYLON.GearVRController = GearVRController;
  67469. })(BABYLON || (BABYLON = {}));
  67470. //# sourceMappingURL=babylon.gearVRController.js.map
  67471. "use strict";
  67472. var BABYLON;
  67473. (function (BABYLON) {
  67474. /**
  67475. * Google Daydream controller
  67476. */
  67477. var DaydreamController = /** @class */ (function (_super) {
  67478. __extends(DaydreamController, _super);
  67479. function DaydreamController(vrGamepad) {
  67480. var _this = _super.call(this, vrGamepad) || this;
  67481. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67482. return _this;
  67483. }
  67484. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67485. var _this = this;
  67486. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67487. _this._defaultModel = newMeshes[1];
  67488. _this.attachToMesh(_this._defaultModel);
  67489. if (meshLoaded) {
  67490. meshLoaded(_this._defaultModel);
  67491. }
  67492. });
  67493. };
  67494. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67495. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67496. if (buttonIdx === 0) {
  67497. var observable = this.onTriggerStateChangedObservable;
  67498. if (observable) {
  67499. observable.notifyObservers(state);
  67500. }
  67501. }
  67502. else {
  67503. // If the app or home buttons are ever made available
  67504. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67505. }
  67506. };
  67507. /**
  67508. * Base Url for the controller model.
  67509. */
  67510. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67511. /**
  67512. * File name for the controller model.
  67513. */
  67514. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67515. /**
  67516. * Gamepad Id prefix used to identify Daydream Controller.
  67517. */
  67518. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67519. return DaydreamController;
  67520. }(BABYLON.WebVRController));
  67521. BABYLON.DaydreamController = DaydreamController;
  67522. })(BABYLON || (BABYLON = {}));
  67523. //# sourceMappingURL=babylon.daydreamController.js.map
  67524. "use strict";
  67525. var BABYLON;
  67526. (function (BABYLON) {
  67527. var FollowCamera = /** @class */ (function (_super) {
  67528. __extends(FollowCamera, _super);
  67529. function FollowCamera(name, position, scene, lockedTarget) {
  67530. if (lockedTarget === void 0) { lockedTarget = null; }
  67531. var _this = _super.call(this, name, position, scene) || this;
  67532. _this.radius = 12;
  67533. _this.rotationOffset = 0;
  67534. _this.heightOffset = 4;
  67535. _this.cameraAcceleration = 0.05;
  67536. _this.maxCameraSpeed = 20;
  67537. _this.lockedTarget = lockedTarget;
  67538. return _this;
  67539. }
  67540. FollowCamera.prototype.getRadians = function (degrees) {
  67541. return degrees * Math.PI / 180;
  67542. };
  67543. FollowCamera.prototype.follow = function (cameraTarget) {
  67544. if (!cameraTarget)
  67545. return;
  67546. var yRotation;
  67547. if (cameraTarget.rotationQuaternion) {
  67548. var rotMatrix = new BABYLON.Matrix();
  67549. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67550. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67551. }
  67552. else {
  67553. yRotation = cameraTarget.rotation.y;
  67554. }
  67555. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67556. var targetPosition = cameraTarget.getAbsolutePosition();
  67557. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67558. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67559. var dx = targetX - this.position.x;
  67560. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67561. var dz = (targetZ) - this.position.z;
  67562. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67563. var vy = dy * this.cameraAcceleration;
  67564. var vz = dz * this.cameraAcceleration * 2;
  67565. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67566. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67567. }
  67568. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67569. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67570. }
  67571. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67572. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67573. }
  67574. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67575. this.setTarget(targetPosition);
  67576. };
  67577. FollowCamera.prototype._checkInputs = function () {
  67578. _super.prototype._checkInputs.call(this);
  67579. if (this.lockedTarget) {
  67580. this.follow(this.lockedTarget);
  67581. }
  67582. };
  67583. FollowCamera.prototype.getClassName = function () {
  67584. return "FollowCamera";
  67585. };
  67586. __decorate([
  67587. BABYLON.serialize()
  67588. ], FollowCamera.prototype, "radius", void 0);
  67589. __decorate([
  67590. BABYLON.serialize()
  67591. ], FollowCamera.prototype, "rotationOffset", void 0);
  67592. __decorate([
  67593. BABYLON.serialize()
  67594. ], FollowCamera.prototype, "heightOffset", void 0);
  67595. __decorate([
  67596. BABYLON.serialize()
  67597. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67598. __decorate([
  67599. BABYLON.serialize()
  67600. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67601. __decorate([
  67602. BABYLON.serializeAsMeshReference("lockedTargetId")
  67603. ], FollowCamera.prototype, "lockedTarget", void 0);
  67604. return FollowCamera;
  67605. }(BABYLON.TargetCamera));
  67606. BABYLON.FollowCamera = FollowCamera;
  67607. var ArcFollowCamera = /** @class */ (function (_super) {
  67608. __extends(ArcFollowCamera, _super);
  67609. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67610. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67611. _this.alpha = alpha;
  67612. _this.beta = beta;
  67613. _this.radius = radius;
  67614. _this.target = target;
  67615. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67616. _this.follow();
  67617. return _this;
  67618. }
  67619. ArcFollowCamera.prototype.follow = function () {
  67620. if (!this.target) {
  67621. return;
  67622. }
  67623. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67624. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67625. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67626. var targetPosition = this.target.getAbsolutePosition();
  67627. this.position = targetPosition.add(this._cartesianCoordinates);
  67628. this.setTarget(targetPosition);
  67629. };
  67630. ArcFollowCamera.prototype._checkInputs = function () {
  67631. _super.prototype._checkInputs.call(this);
  67632. this.follow();
  67633. };
  67634. ArcFollowCamera.prototype.getClassName = function () {
  67635. return "ArcFollowCamera";
  67636. };
  67637. return ArcFollowCamera;
  67638. }(BABYLON.TargetCamera));
  67639. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67640. })(BABYLON || (BABYLON = {}));
  67641. //# sourceMappingURL=babylon.followCamera.js.map
  67642. "use strict";
  67643. var BABYLON;
  67644. (function (BABYLON) {
  67645. // We're mainly based on the logic defined into the FreeCamera code
  67646. var UniversalCamera = /** @class */ (function (_super) {
  67647. __extends(UniversalCamera, _super);
  67648. //-- end properties for backward compatibility for inputs
  67649. function UniversalCamera(name, position, scene) {
  67650. var _this = _super.call(this, name, position, scene) || this;
  67651. _this.inputs.addGamepad();
  67652. return _this;
  67653. }
  67654. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67655. //-- Begin properties for backward compatibility for inputs
  67656. get: function () {
  67657. var gamepad = this.inputs.attached["gamepad"];
  67658. if (gamepad)
  67659. return gamepad.gamepadAngularSensibility;
  67660. return 0;
  67661. },
  67662. set: function (value) {
  67663. var gamepad = this.inputs.attached["gamepad"];
  67664. if (gamepad)
  67665. gamepad.gamepadAngularSensibility = value;
  67666. },
  67667. enumerable: true,
  67668. configurable: true
  67669. });
  67670. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67671. get: function () {
  67672. var gamepad = this.inputs.attached["gamepad"];
  67673. if (gamepad)
  67674. return gamepad.gamepadMoveSensibility;
  67675. return 0;
  67676. },
  67677. set: function (value) {
  67678. var gamepad = this.inputs.attached["gamepad"];
  67679. if (gamepad)
  67680. gamepad.gamepadMoveSensibility = value;
  67681. },
  67682. enumerable: true,
  67683. configurable: true
  67684. });
  67685. UniversalCamera.prototype.getClassName = function () {
  67686. return "UniversalCamera";
  67687. };
  67688. return UniversalCamera;
  67689. }(BABYLON.TouchCamera));
  67690. BABYLON.UniversalCamera = UniversalCamera;
  67691. })(BABYLON || (BABYLON = {}));
  67692. //# sourceMappingURL=babylon.universalCamera.js.map
  67693. "use strict";
  67694. var BABYLON;
  67695. (function (BABYLON) {
  67696. // We're mainly based on the logic defined into the FreeCamera code
  67697. var GamepadCamera = /** @class */ (function (_super) {
  67698. __extends(GamepadCamera, _super);
  67699. //-- end properties for backward compatibility for inputs
  67700. function GamepadCamera(name, position, scene) {
  67701. return _super.call(this, name, position, scene) || this;
  67702. }
  67703. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67704. //-- Begin properties for backward compatibility for inputs
  67705. get: function () {
  67706. var gamepad = this.inputs.attached["gamepad"];
  67707. if (gamepad)
  67708. return gamepad.gamepadAngularSensibility;
  67709. return 0;
  67710. },
  67711. set: function (value) {
  67712. var gamepad = this.inputs.attached["gamepad"];
  67713. if (gamepad)
  67714. gamepad.gamepadAngularSensibility = value;
  67715. },
  67716. enumerable: true,
  67717. configurable: true
  67718. });
  67719. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67720. get: function () {
  67721. var gamepad = this.inputs.attached["gamepad"];
  67722. if (gamepad)
  67723. return gamepad.gamepadMoveSensibility;
  67724. return 0;
  67725. },
  67726. set: function (value) {
  67727. var gamepad = this.inputs.attached["gamepad"];
  67728. if (gamepad)
  67729. gamepad.gamepadMoveSensibility = value;
  67730. },
  67731. enumerable: true,
  67732. configurable: true
  67733. });
  67734. GamepadCamera.prototype.getClassName = function () {
  67735. return "GamepadCamera";
  67736. };
  67737. return GamepadCamera;
  67738. }(BABYLON.UniversalCamera));
  67739. BABYLON.GamepadCamera = GamepadCamera;
  67740. })(BABYLON || (BABYLON = {}));
  67741. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67742. "use strict";
  67743. var BABYLON;
  67744. (function (BABYLON) {
  67745. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67746. function PostProcessRenderPipelineManager() {
  67747. this._renderPipelines = {};
  67748. }
  67749. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67750. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67751. };
  67752. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67753. if (unique === void 0) { unique = false; }
  67754. var renderPipeline = this._renderPipelines[renderPipelineName];
  67755. if (!renderPipeline) {
  67756. return;
  67757. }
  67758. renderPipeline._attachCameras(cameras, unique);
  67759. };
  67760. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67761. var renderPipeline = this._renderPipelines[renderPipelineName];
  67762. if (!renderPipeline) {
  67763. return;
  67764. }
  67765. renderPipeline._detachCameras(cameras);
  67766. };
  67767. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67768. var renderPipeline = this._renderPipelines[renderPipelineName];
  67769. if (!renderPipeline) {
  67770. return;
  67771. }
  67772. renderPipeline._enableEffect(renderEffectName, cameras);
  67773. };
  67774. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67775. var renderPipeline = this._renderPipelines[renderPipelineName];
  67776. if (!renderPipeline) {
  67777. return;
  67778. }
  67779. renderPipeline._disableEffect(renderEffectName, cameras);
  67780. };
  67781. PostProcessRenderPipelineManager.prototype.update = function () {
  67782. for (var renderPipelineName in this._renderPipelines) {
  67783. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67784. var pipeline = this._renderPipelines[renderPipelineName];
  67785. if (!pipeline.isSupported) {
  67786. pipeline.dispose();
  67787. delete this._renderPipelines[renderPipelineName];
  67788. }
  67789. else {
  67790. pipeline._update();
  67791. }
  67792. }
  67793. }
  67794. };
  67795. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67796. for (var renderPipelineName in this._renderPipelines) {
  67797. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67798. var pipeline = this._renderPipelines[renderPipelineName];
  67799. pipeline._rebuild();
  67800. }
  67801. }
  67802. };
  67803. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67804. for (var renderPipelineName in this._renderPipelines) {
  67805. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67806. var pipeline = this._renderPipelines[renderPipelineName];
  67807. pipeline.dispose();
  67808. }
  67809. }
  67810. };
  67811. return PostProcessRenderPipelineManager;
  67812. }());
  67813. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67814. })(BABYLON || (BABYLON = {}));
  67815. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67816. "use strict";
  67817. var BABYLON;
  67818. (function (BABYLON) {
  67819. /**
  67820. * This represents a set of one or more post processes in Babylon.
  67821. * A post process can be used to apply a shader to a texture after it is rendered.
  67822. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67823. */
  67824. var PostProcessRenderEffect = /** @class */ (function () {
  67825. /**
  67826. * Instantiates a post process render effect.
  67827. * A post process can be used to apply a shader to a texture after it is rendered.
  67828. * @param engine The engine the effect is tied to
  67829. * @param name The name of the effect
  67830. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67831. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67832. */
  67833. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67834. this._name = name;
  67835. this._singleInstance = singleInstance || true;
  67836. this._getPostProcesses = getPostProcesses;
  67837. this._cameras = {};
  67838. this._indicesForCamera = {};
  67839. this._postProcesses = {};
  67840. }
  67841. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67842. /**
  67843. * Checks if all the post processes in the effect are supported.
  67844. */
  67845. get: function () {
  67846. for (var index in this._postProcesses) {
  67847. for (var ppIndex in this._postProcesses[index]) {
  67848. if (!this._postProcesses[index][ppIndex].isSupported) {
  67849. return false;
  67850. }
  67851. }
  67852. }
  67853. return true;
  67854. },
  67855. enumerable: true,
  67856. configurable: true
  67857. });
  67858. /**
  67859. * Updates the current state of the effect
  67860. */
  67861. PostProcessRenderEffect.prototype._update = function () {
  67862. };
  67863. /**
  67864. * Attaches the effect on cameras
  67865. * @param cameras The camera to attach to.
  67866. */
  67867. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67868. var _this = this;
  67869. var cameraKey;
  67870. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67871. if (!cams) {
  67872. return;
  67873. }
  67874. for (var i = 0; i < cams.length; i++) {
  67875. var camera = cams[i];
  67876. var cameraName = camera.name;
  67877. if (this._singleInstance) {
  67878. cameraKey = 0;
  67879. }
  67880. else {
  67881. cameraKey = cameraName;
  67882. }
  67883. if (!this._postProcesses[cameraKey]) {
  67884. var postProcess = this._getPostProcesses();
  67885. if (postProcess) {
  67886. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67887. }
  67888. }
  67889. if (!this._indicesForCamera[cameraName]) {
  67890. this._indicesForCamera[cameraName] = [];
  67891. }
  67892. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67893. var index = camera.attachPostProcess(postProcess);
  67894. _this._indicesForCamera[cameraName].push(index);
  67895. });
  67896. if (!this._cameras[cameraName]) {
  67897. this._cameras[cameraName] = camera;
  67898. }
  67899. }
  67900. };
  67901. /**
  67902. * Detatches the effect on cameras
  67903. * @param cameras The camera to detatch from.
  67904. */
  67905. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67906. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67907. if (!cams) {
  67908. return;
  67909. }
  67910. for (var i = 0; i < cams.length; i++) {
  67911. var camera = cams[i];
  67912. var cameraName = camera.name;
  67913. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67914. camera.detachPostProcess(postProcess);
  67915. });
  67916. if (this._cameras[cameraName]) {
  67917. //this._indicesForCamera.splice(index, 1);
  67918. this._cameras[cameraName] = null;
  67919. }
  67920. }
  67921. };
  67922. /**
  67923. * Enables the effect on given cameras
  67924. * @param cameras The camera to enable.
  67925. */
  67926. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67927. var _this = this;
  67928. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67929. if (!cams) {
  67930. return;
  67931. }
  67932. for (var i = 0; i < cams.length; i++) {
  67933. var camera = cams[i];
  67934. var cameraName = camera.name;
  67935. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67936. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67937. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67938. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67939. });
  67940. }
  67941. }
  67942. }
  67943. };
  67944. /**
  67945. * Disables the effect on the given cameras
  67946. * @param cameras The camera to disable.
  67947. */
  67948. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67949. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67950. if (!cams) {
  67951. return;
  67952. }
  67953. for (var i = 0; i < cams.length; i++) {
  67954. var camera = cams[i];
  67955. var cameraName = camera.name;
  67956. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67957. camera.detachPostProcess(postProcess);
  67958. });
  67959. }
  67960. };
  67961. /**
  67962. * Gets a list of the post processes contained in the effect.
  67963. * @param camera The camera to get the post processes on.
  67964. * @returns The list of the post processes in the effect.
  67965. */
  67966. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67967. if (this._singleInstance) {
  67968. return this._postProcesses[0];
  67969. }
  67970. else {
  67971. if (!camera) {
  67972. return null;
  67973. }
  67974. return this._postProcesses[camera.name];
  67975. }
  67976. };
  67977. return PostProcessRenderEffect;
  67978. }());
  67979. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67980. })(BABYLON || (BABYLON = {}));
  67981. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67982. "use strict";
  67983. var BABYLON;
  67984. (function (BABYLON) {
  67985. var PostProcessRenderPipeline = /** @class */ (function () {
  67986. function PostProcessRenderPipeline(engine, name) {
  67987. this.engine = engine;
  67988. this._name = name;
  67989. this._renderEffects = {};
  67990. this._renderEffectsForIsolatedPass = new Array();
  67991. this._cameras = [];
  67992. }
  67993. PostProcessRenderPipeline.prototype.getClassName = function () {
  67994. return "PostProcessRenderPipeline";
  67995. };
  67996. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67997. get: function () {
  67998. for (var renderEffectName in this._renderEffects) {
  67999. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68000. if (!this._renderEffects[renderEffectName].isSupported) {
  68001. return false;
  68002. }
  68003. }
  68004. }
  68005. return true;
  68006. },
  68007. enumerable: true,
  68008. configurable: true
  68009. });
  68010. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  68011. this._renderEffects[renderEffect._name] = renderEffect;
  68012. };
  68013. // private
  68014. PostProcessRenderPipeline.prototype._rebuild = function () {
  68015. };
  68016. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  68017. var renderEffects = this._renderEffects[renderEffectName];
  68018. if (!renderEffects) {
  68019. return;
  68020. }
  68021. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68022. };
  68023. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  68024. var renderEffects = this._renderEffects[renderEffectName];
  68025. if (!renderEffects) {
  68026. return;
  68027. }
  68028. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  68029. };
  68030. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  68031. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68032. if (!cams) {
  68033. return;
  68034. }
  68035. var indicesToDelete = [];
  68036. var i;
  68037. for (i = 0; i < cams.length; i++) {
  68038. var camera = cams[i];
  68039. var cameraName = camera.name;
  68040. if (this._cameras.indexOf(camera) === -1) {
  68041. this._cameras[cameraName] = camera;
  68042. }
  68043. else if (unique) {
  68044. indicesToDelete.push(i);
  68045. }
  68046. }
  68047. for (i = 0; i < indicesToDelete.length; i++) {
  68048. cameras.splice(indicesToDelete[i], 1);
  68049. }
  68050. for (var renderEffectName in this._renderEffects) {
  68051. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68052. this._renderEffects[renderEffectName]._attachCameras(cams);
  68053. }
  68054. }
  68055. };
  68056. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  68057. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  68058. if (!cams) {
  68059. return;
  68060. }
  68061. for (var renderEffectName in this._renderEffects) {
  68062. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68063. this._renderEffects[renderEffectName]._detachCameras(cams);
  68064. }
  68065. }
  68066. for (var i = 0; i < cams.length; i++) {
  68067. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  68068. }
  68069. };
  68070. PostProcessRenderPipeline.prototype._update = function () {
  68071. for (var renderEffectName in this._renderEffects) {
  68072. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  68073. this._renderEffects[renderEffectName]._update();
  68074. }
  68075. }
  68076. for (var i = 0; i < this._cameras.length; i++) {
  68077. var cameraName = this._cameras[i].name;
  68078. if (this._renderEffectsForIsolatedPass[cameraName]) {
  68079. this._renderEffectsForIsolatedPass[cameraName]._update();
  68080. }
  68081. }
  68082. };
  68083. PostProcessRenderPipeline.prototype._reset = function () {
  68084. this._renderEffects = {};
  68085. this._renderEffectsForIsolatedPass = new Array();
  68086. };
  68087. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  68088. // 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)
  68089. var effectKeys = Object.keys(this._renderEffects);
  68090. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  68091. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  68092. if (postProcesses) {
  68093. postProcesses[0].samples = sampleCount;
  68094. return true;
  68095. }
  68096. }
  68097. return false;
  68098. };
  68099. PostProcessRenderPipeline.prototype.dispose = function () {
  68100. // Must be implemented by children
  68101. };
  68102. __decorate([
  68103. BABYLON.serialize()
  68104. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  68105. return PostProcessRenderPipeline;
  68106. }());
  68107. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  68108. })(BABYLON || (BABYLON = {}));
  68109. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  68110. "use strict";
  68111. var BABYLON;
  68112. (function (BABYLON) {
  68113. /**
  68114. * This represents a depth renderer in Babylon.
  68115. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  68116. */
  68117. var DepthRenderer = /** @class */ (function () {
  68118. /**
  68119. * Instantiates a depth renderer
  68120. * @param scene The scene the renderer belongs to
  68121. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  68122. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  68123. */
  68124. function DepthRenderer(scene, type, camera) {
  68125. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  68126. if (camera === void 0) { camera = null; }
  68127. var _this = this;
  68128. this._scene = scene;
  68129. this._camera = camera;
  68130. var engine = scene.getEngine();
  68131. // Render target
  68132. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  68133. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68134. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68135. this._depthMap.refreshRate = 1;
  68136. this._depthMap.renderParticles = false;
  68137. this._depthMap.renderList = null;
  68138. // Camera to get depth map from to support multiple concurrent cameras
  68139. this._depthMap.activeCamera = this._camera;
  68140. this._depthMap.ignoreCameraViewport = true;
  68141. this._depthMap.useCameraPostProcesses = false;
  68142. // set default depth value to 1.0 (far away)
  68143. this._depthMap.onClearObservable.add(function (engine) {
  68144. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  68145. });
  68146. // Custom render function
  68147. var renderSubMesh = function (subMesh) {
  68148. var mesh = subMesh.getRenderingMesh();
  68149. var scene = _this._scene;
  68150. var engine = scene.getEngine();
  68151. var material = subMesh.getMaterial();
  68152. if (!material) {
  68153. return;
  68154. }
  68155. // Culling and reverse (right handed system)
  68156. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68157. // Managing instances
  68158. var batch = mesh._getInstancesRenderList(subMesh._id);
  68159. if (batch.mustReturn) {
  68160. return;
  68161. }
  68162. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68163. var camera = _this._camera || scene.activeCamera;
  68164. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  68165. engine.enableEffect(_this._effect);
  68166. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68167. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68168. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  68169. // Alpha test
  68170. if (material && material.needAlphaTesting()) {
  68171. var alphaTexture = material.getAlphaTestTexture();
  68172. if (alphaTexture) {
  68173. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68174. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68175. }
  68176. }
  68177. // Bones
  68178. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68179. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68180. }
  68181. // Draw
  68182. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68183. }
  68184. };
  68185. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68186. var index;
  68187. if (depthOnlySubMeshes.length) {
  68188. engine.setColorWrite(false);
  68189. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68190. renderSubMesh(depthOnlySubMeshes.data[index]);
  68191. }
  68192. engine.setColorWrite(true);
  68193. }
  68194. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68195. renderSubMesh(opaqueSubMeshes.data[index]);
  68196. }
  68197. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68198. renderSubMesh(alphaTestSubMeshes.data[index]);
  68199. }
  68200. };
  68201. }
  68202. /**
  68203. * Creates the depth rendering effect and checks if the effect is ready.
  68204. * @param subMesh The submesh to be used to render the depth map of
  68205. * @param useInstances If multiple world instances should be used
  68206. * @returns if the depth renderer is ready to render the depth map
  68207. */
  68208. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  68209. var material = subMesh.getMaterial();
  68210. if (material.disableDepthWrite) {
  68211. return false;
  68212. }
  68213. var defines = [];
  68214. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68215. var mesh = subMesh.getMesh();
  68216. // Alpha test
  68217. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  68218. defines.push("#define ALPHATEST");
  68219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68220. attribs.push(BABYLON.VertexBuffer.UVKind);
  68221. defines.push("#define UV1");
  68222. }
  68223. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68224. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68225. defines.push("#define UV2");
  68226. }
  68227. }
  68228. // Bones
  68229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68232. if (mesh.numBoneInfluencers > 4) {
  68233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68235. }
  68236. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68237. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68238. }
  68239. else {
  68240. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68241. }
  68242. // Instances
  68243. if (useInstances) {
  68244. defines.push("#define INSTANCES");
  68245. attribs.push("world0");
  68246. attribs.push("world1");
  68247. attribs.push("world2");
  68248. attribs.push("world3");
  68249. }
  68250. // Get correct effect
  68251. var join = defines.join("\n");
  68252. if (this._cachedDefines !== join) {
  68253. this._cachedDefines = join;
  68254. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  68255. }
  68256. return this._effect.isReady();
  68257. };
  68258. /**
  68259. * Gets the texture which the depth map will be written to.
  68260. * @returns The depth map texture
  68261. */
  68262. DepthRenderer.prototype.getDepthMap = function () {
  68263. return this._depthMap;
  68264. };
  68265. /**
  68266. * Disposes of the depth renderer.
  68267. */
  68268. DepthRenderer.prototype.dispose = function () {
  68269. this._depthMap.dispose();
  68270. };
  68271. return DepthRenderer;
  68272. }());
  68273. BABYLON.DepthRenderer = DepthRenderer;
  68274. })(BABYLON || (BABYLON = {}));
  68275. //# sourceMappingURL=babylon.depthRenderer.js.map
  68276. "use strict";
  68277. var BABYLON;
  68278. (function (BABYLON) {
  68279. var SSAORenderingPipeline = /** @class */ (function (_super) {
  68280. __extends(SSAORenderingPipeline, _super);
  68281. /**
  68282. * @constructor
  68283. * @param {string} name - The rendering pipeline name
  68284. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68285. * @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 }
  68286. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68287. */
  68288. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  68289. var _this = _super.call(this, scene.getEngine(), name) || this;
  68290. // Members
  68291. /**
  68292. * The PassPostProcess id in the pipeline that contains the original scene color
  68293. * @type {string}
  68294. */
  68295. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68296. /**
  68297. * The SSAO PostProcess id in the pipeline
  68298. * @type {string}
  68299. */
  68300. _this.SSAORenderEffect = "SSAORenderEffect";
  68301. /**
  68302. * The horizontal blur PostProcess id in the pipeline
  68303. * @type {string}
  68304. */
  68305. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68306. /**
  68307. * The vertical blur PostProcess id in the pipeline
  68308. * @type {string}
  68309. */
  68310. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68311. /**
  68312. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68313. * @type {string}
  68314. */
  68315. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68316. /**
  68317. * The output strength of the SSAO post-process. Default value is 1.0.
  68318. * @type {number}
  68319. */
  68320. _this.totalStrength = 1.0;
  68321. /**
  68322. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68323. * @type {number}
  68324. */
  68325. _this.radius = 0.0001;
  68326. /**
  68327. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68328. * Must not be equal to fallOff and superior to fallOff.
  68329. * Default value is 0.975
  68330. * @type {number}
  68331. */
  68332. _this.area = 0.0075;
  68333. /**
  68334. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68335. * Must not be equal to area and inferior to area.
  68336. * Default value is 0.0
  68337. * @type {number}
  68338. */
  68339. _this.fallOff = 0.000001;
  68340. /**
  68341. * The base color of the SSAO post-process
  68342. * The final result is "base + ssao" between [0, 1]
  68343. * @type {number}
  68344. */
  68345. _this.base = 0.5;
  68346. _this._firstUpdate = true;
  68347. _this._scene = scene;
  68348. // Set up assets
  68349. _this._createRandomTexture();
  68350. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68351. var ssaoRatio = ratio.ssaoRatio || ratio;
  68352. var combineRatio = ratio.combineRatio || ratio;
  68353. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68354. _this._createSSAOPostProcess(ssaoRatio);
  68355. _this._createBlurPostProcess(ssaoRatio);
  68356. _this._createSSAOCombinePostProcess(combineRatio);
  68357. // Set up pipeline
  68358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68361. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68362. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68363. // Finish
  68364. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68365. if (cameras)
  68366. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68367. return _this;
  68368. }
  68369. // Public Methods
  68370. /**
  68371. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68372. */
  68373. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68374. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68375. for (var i = 0; i < this._scene.cameras.length; i++) {
  68376. var camera = this._scene.cameras[i];
  68377. this._originalColorPostProcess.dispose(camera);
  68378. this._ssaoPostProcess.dispose(camera);
  68379. this._blurHPostProcess.dispose(camera);
  68380. this._blurVPostProcess.dispose(camera);
  68381. this._ssaoCombinePostProcess.dispose(camera);
  68382. }
  68383. this._randomTexture.dispose();
  68384. if (disableDepthRender)
  68385. this._scene.disableDepthRenderer();
  68386. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68387. _super.prototype.dispose.call(this);
  68388. };
  68389. // Private Methods
  68390. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68391. var _this = this;
  68392. var size = 16;
  68393. 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);
  68394. 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);
  68395. this._blurHPostProcess.onActivateObservable.add(function () {
  68396. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68397. _this._blurHPostProcess.kernel = size * dw;
  68398. });
  68399. this._blurVPostProcess.onActivateObservable.add(function () {
  68400. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68401. _this._blurVPostProcess.kernel = size * dw;
  68402. });
  68403. };
  68404. SSAORenderingPipeline.prototype._rebuild = function () {
  68405. this._firstUpdate = true;
  68406. _super.prototype._rebuild.call(this);
  68407. };
  68408. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68409. var _this = this;
  68410. var numSamples = 16;
  68411. var sampleSphere = [
  68412. 0.5381, 0.1856, -0.4319,
  68413. 0.1379, 0.2486, 0.4430,
  68414. 0.3371, 0.5679, -0.0057,
  68415. -0.6999, -0.0451, -0.0019,
  68416. 0.0689, -0.1598, -0.8547,
  68417. 0.0560, 0.0069, -0.1843,
  68418. -0.0146, 0.1402, 0.0762,
  68419. 0.0100, -0.1924, -0.0344,
  68420. -0.3577, -0.5301, -0.4358,
  68421. -0.3169, 0.1063, 0.0158,
  68422. 0.0103, -0.5869, 0.0046,
  68423. -0.0897, -0.4940, 0.3287,
  68424. 0.7119, -0.0154, -0.0918,
  68425. -0.0533, 0.0596, -0.5411,
  68426. 0.0352, -0.0631, 0.5460,
  68427. -0.4776, 0.2847, -0.0271
  68428. ];
  68429. var samplesFactor = 1.0 / numSamples;
  68430. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68431. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68432. "area", "fallOff", "base", "range", "viewport"
  68433. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68434. this._ssaoPostProcess.onApply = function (effect) {
  68435. if (_this._firstUpdate) {
  68436. effect.setArray3("sampleSphere", sampleSphere);
  68437. effect.setFloat("samplesFactor", samplesFactor);
  68438. effect.setFloat("randTextureTiles", 4.0);
  68439. }
  68440. effect.setFloat("totalStrength", _this.totalStrength);
  68441. effect.setFloat("radius", _this.radius);
  68442. effect.setFloat("area", _this.area);
  68443. effect.setFloat("fallOff", _this.fallOff);
  68444. effect.setFloat("base", _this.base);
  68445. effect.setTexture("textureSampler", _this._depthTexture);
  68446. effect.setTexture("randomSampler", _this._randomTexture);
  68447. };
  68448. };
  68449. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68450. var _this = this;
  68451. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68452. this._ssaoCombinePostProcess.onApply = function (effect) {
  68453. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68454. };
  68455. };
  68456. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68457. var size = 512;
  68458. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68459. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68460. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68461. var context = this._randomTexture.getContext();
  68462. var rand = function (min, max) {
  68463. return Math.random() * (max - min) + min;
  68464. };
  68465. var randVector = BABYLON.Vector3.Zero();
  68466. for (var x = 0; x < size; x++) {
  68467. for (var y = 0; y < size; y++) {
  68468. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68469. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68470. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68471. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68472. context.fillRect(x, y, 1, 1);
  68473. }
  68474. }
  68475. this._randomTexture.update(false);
  68476. };
  68477. __decorate([
  68478. BABYLON.serialize()
  68479. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68480. __decorate([
  68481. BABYLON.serialize()
  68482. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68483. __decorate([
  68484. BABYLON.serialize()
  68485. ], SSAORenderingPipeline.prototype, "area", void 0);
  68486. __decorate([
  68487. BABYLON.serialize()
  68488. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68489. __decorate([
  68490. BABYLON.serialize()
  68491. ], SSAORenderingPipeline.prototype, "base", void 0);
  68492. return SSAORenderingPipeline;
  68493. }(BABYLON.PostProcessRenderPipeline));
  68494. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68495. })(BABYLON || (BABYLON = {}));
  68496. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68497. "use strict";
  68498. var BABYLON;
  68499. (function (BABYLON) {
  68500. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68501. __extends(SSAO2RenderingPipeline, _super);
  68502. /**
  68503. * @constructor
  68504. * @param {string} name - The rendering pipeline name
  68505. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68506. * @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 }
  68507. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68508. */
  68509. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68510. var _this = _super.call(this, scene.getEngine(), name) || this;
  68511. // Members
  68512. /**
  68513. * The PassPostProcess id in the pipeline that contains the original scene color
  68514. * @type {string}
  68515. */
  68516. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68517. /**
  68518. * The SSAO PostProcess id in the pipeline
  68519. * @type {string}
  68520. */
  68521. _this.SSAORenderEffect = "SSAORenderEffect";
  68522. /**
  68523. * The horizontal blur PostProcess id in the pipeline
  68524. * @type {string}
  68525. */
  68526. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68527. /**
  68528. * The vertical blur PostProcess id in the pipeline
  68529. * @type {string}
  68530. */
  68531. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68532. /**
  68533. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68534. * @type {string}
  68535. */
  68536. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68537. /**
  68538. * The output strength of the SSAO post-process. Default value is 1.0.
  68539. * @type {number}
  68540. */
  68541. _this.totalStrength = 1.0;
  68542. /**
  68543. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68544. * @type {number}
  68545. */
  68546. _this.maxZ = 100.0;
  68547. /**
  68548. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68549. * @type {number}
  68550. */
  68551. _this.minZAspect = 0.2;
  68552. /**
  68553. * Number of samples used for the SSAO calculations. Default value is 8
  68554. * @type {number}
  68555. */
  68556. _this._samples = 8;
  68557. /**
  68558. * Are we using bilateral blur ?
  68559. * @type {boolean}
  68560. */
  68561. _this._expensiveBlur = true;
  68562. /**
  68563. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68564. * @type {number}
  68565. */
  68566. _this.radius = 2.0;
  68567. /**
  68568. * The base color of the SSAO post-process
  68569. * The final result is "base + ssao" between [0, 1]
  68570. * @type {number}
  68571. */
  68572. _this.base = 0.1;
  68573. _this._firstUpdate = true;
  68574. _this._scene = scene;
  68575. if (!_this.isSupported) {
  68576. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68577. return _this;
  68578. }
  68579. var ssaoRatio = ratio.ssaoRatio || ratio;
  68580. var blurRatio = ratio.blurRatio || ratio;
  68581. // Set up assets
  68582. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68583. _this._createRandomTexture();
  68584. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68585. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68586. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68587. _this._createSSAOPostProcess(1.0);
  68588. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68589. _this._createSSAOCombinePostProcess(blurRatio);
  68590. // Set up pipeline
  68591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68592. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68593. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68594. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68595. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68596. // Finish
  68597. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68598. if (cameras)
  68599. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68600. return _this;
  68601. }
  68602. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68603. get: function () {
  68604. return this._samples;
  68605. },
  68606. set: function (n) {
  68607. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68608. this._samples = n;
  68609. this._sampleSphere = this._generateHemisphere();
  68610. this._firstUpdate = true;
  68611. },
  68612. enumerable: true,
  68613. configurable: true
  68614. });
  68615. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68616. get: function () {
  68617. return this._expensiveBlur;
  68618. },
  68619. set: function (b) {
  68620. 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"]);
  68621. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68622. this._expensiveBlur = b;
  68623. this._firstUpdate = true;
  68624. },
  68625. enumerable: true,
  68626. configurable: true
  68627. });
  68628. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68629. /**
  68630. * Support test.
  68631. * @type {boolean}
  68632. */
  68633. get: function () {
  68634. var engine = BABYLON.Engine.LastCreatedEngine;
  68635. if (!engine) {
  68636. return false;
  68637. }
  68638. return engine.getCaps().drawBuffersExtension;
  68639. },
  68640. enumerable: true,
  68641. configurable: true
  68642. });
  68643. // Public Methods
  68644. /**
  68645. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68646. */
  68647. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68648. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68649. for (var i = 0; i < this._scene.cameras.length; i++) {
  68650. var camera = this._scene.cameras[i];
  68651. this._originalColorPostProcess.dispose(camera);
  68652. this._ssaoPostProcess.dispose(camera);
  68653. this._blurHPostProcess.dispose(camera);
  68654. this._blurVPostProcess.dispose(camera);
  68655. this._ssaoCombinePostProcess.dispose(camera);
  68656. }
  68657. this._randomTexture.dispose();
  68658. if (disableGeometryBufferRenderer)
  68659. this._scene.disableGeometryBufferRenderer();
  68660. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68661. _super.prototype.dispose.call(this);
  68662. };
  68663. // Private Methods
  68664. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68665. var _this = this;
  68666. this._samplerOffsets = [];
  68667. var expensive = this.expensiveBlur;
  68668. for (var i = -8; i < 8; i++) {
  68669. this._samplerOffsets.push(i * 2 + 0.5);
  68670. }
  68671. 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");
  68672. this._blurHPostProcess.onApply = function (effect) {
  68673. if (!_this._scene.activeCamera) {
  68674. return;
  68675. }
  68676. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68677. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68678. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68679. effect.setFloat("radius", _this.radius);
  68680. effect.setTexture("depthSampler", _this._depthTexture);
  68681. if (_this._firstUpdate) {
  68682. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68683. }
  68684. };
  68685. 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");
  68686. this._blurVPostProcess.onApply = function (effect) {
  68687. if (!_this._scene.activeCamera) {
  68688. return;
  68689. }
  68690. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68691. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68692. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68693. effect.setFloat("radius", _this.radius);
  68694. effect.setTexture("depthSampler", _this._depthTexture);
  68695. if (_this._firstUpdate) {
  68696. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68697. _this._firstUpdate = false;
  68698. }
  68699. };
  68700. };
  68701. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68702. this._firstUpdate = true;
  68703. _super.prototype._rebuild.call(this);
  68704. };
  68705. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68706. var numSamples = this.samples;
  68707. var result = [];
  68708. var vector, scale;
  68709. var rand = function (min, max) {
  68710. return Math.random() * (max - min) + min;
  68711. };
  68712. var i = 0;
  68713. while (i < numSamples) {
  68714. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68715. vector.normalize();
  68716. scale = i / numSamples;
  68717. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68718. vector.scaleInPlace(scale);
  68719. result.push(vector.x, vector.y, vector.z);
  68720. i++;
  68721. }
  68722. return result;
  68723. };
  68724. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68725. var _this = this;
  68726. var numSamples = this.samples;
  68727. this._sampleSphere = this._generateHemisphere();
  68728. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68729. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68730. "base", "range", "projection", "near", "far", "texelSize",
  68731. "xViewport", "yViewport", "maxZ", "minZAspect"
  68732. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68733. this._ssaoPostProcess.onApply = function (effect) {
  68734. if (_this._firstUpdate) {
  68735. effect.setArray3("sampleSphere", _this._sampleSphere);
  68736. effect.setFloat("randTextureTiles", 4.0);
  68737. }
  68738. if (!_this._scene.activeCamera) {
  68739. return;
  68740. }
  68741. effect.setFloat("samplesFactor", 1 / _this.samples);
  68742. effect.setFloat("totalStrength", _this.totalStrength);
  68743. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68744. effect.setFloat("radius", _this.radius);
  68745. effect.setFloat("maxZ", _this.maxZ);
  68746. effect.setFloat("minZAspect", _this.minZAspect);
  68747. effect.setFloat("base", _this.base);
  68748. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68749. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68750. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68751. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68752. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68753. effect.setTexture("textureSampler", _this._depthTexture);
  68754. effect.setTexture("normalSampler", _this._normalTexture);
  68755. effect.setTexture("randomSampler", _this._randomTexture);
  68756. };
  68757. };
  68758. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68759. var _this = this;
  68760. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68761. this._ssaoCombinePostProcess.onApply = function (effect) {
  68762. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68763. };
  68764. };
  68765. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68766. var size = 512;
  68767. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68768. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68769. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68770. var context = this._randomTexture.getContext();
  68771. var rand = function (min, max) {
  68772. return Math.random() * (max - min) + min;
  68773. };
  68774. var randVector = BABYLON.Vector3.Zero();
  68775. for (var x = 0; x < size; x++) {
  68776. for (var y = 0; y < size; y++) {
  68777. randVector.x = rand(0.0, 1.0);
  68778. randVector.y = rand(0.0, 1.0);
  68779. randVector.z = 0.0;
  68780. randVector.normalize();
  68781. randVector.scaleInPlace(255);
  68782. randVector.x = Math.floor(randVector.x);
  68783. randVector.y = Math.floor(randVector.y);
  68784. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68785. context.fillRect(x, y, 1, 1);
  68786. }
  68787. }
  68788. this._randomTexture.update(false);
  68789. };
  68790. __decorate([
  68791. BABYLON.serialize()
  68792. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68793. __decorate([
  68794. BABYLON.serialize()
  68795. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68796. __decorate([
  68797. BABYLON.serialize()
  68798. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68799. __decorate([
  68800. BABYLON.serialize("samples")
  68801. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68802. __decorate([
  68803. BABYLON.serialize("expensiveBlur")
  68804. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68805. __decorate([
  68806. BABYLON.serialize()
  68807. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68808. __decorate([
  68809. BABYLON.serialize()
  68810. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68811. return SSAO2RenderingPipeline;
  68812. }(BABYLON.PostProcessRenderPipeline));
  68813. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68814. })(BABYLON || (BABYLON = {}));
  68815. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68816. "use strict";
  68817. // BABYLON.JS Chromatic Aberration GLSL Shader
  68818. // Author: Olivier Guyot
  68819. // Separates very slightly R, G and B colors on the edges of the screen
  68820. // Inspired by Francois Tarlier & Martins Upitis
  68821. var BABYLON;
  68822. (function (BABYLON) {
  68823. var LensRenderingPipeline = /** @class */ (function (_super) {
  68824. __extends(LensRenderingPipeline, _super);
  68825. /**
  68826. * @constructor
  68827. *
  68828. * Effect parameters are as follow:
  68829. * {
  68830. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68831. * edge_blur: number; // from 0 to x (1 for realism)
  68832. * distortion: number; // from 0 to x (1 for realism)
  68833. * grain_amount: number; // from 0 to 1
  68834. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68835. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68836. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68837. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68838. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68839. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68840. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68841. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68842. * }
  68843. * Note: if an effect parameter is unset, effect is disabled
  68844. *
  68845. * @param {string} name - The rendering pipeline name
  68846. * @param {object} parameters - An object containing all parameters (see above)
  68847. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68848. * @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)
  68849. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68850. */
  68851. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68852. if (ratio === void 0) { ratio = 1.0; }
  68853. var _this = _super.call(this, scene.getEngine(), name) || this;
  68854. // Lens effects can be of the following:
  68855. // - chromatic aberration (slight shift of RGB colors)
  68856. // - blur on the edge of the lens
  68857. // - lens distortion
  68858. // - depth-of-field blur & highlights enhancing
  68859. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68860. // - grain effect (noise or custom texture)
  68861. // Two additional texture samplers are needed:
  68862. // - depth map (for depth-of-field)
  68863. // - grain texture
  68864. /**
  68865. * The chromatic aberration PostProcess id in the pipeline
  68866. * @type {string}
  68867. */
  68868. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68869. /**
  68870. * The highlights enhancing PostProcess id in the pipeline
  68871. * @type {string}
  68872. */
  68873. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68874. /**
  68875. * The depth-of-field PostProcess id in the pipeline
  68876. * @type {string}
  68877. */
  68878. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68879. _this._scene = scene;
  68880. // Fetch texture samplers
  68881. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68882. if (parameters.grain_texture) {
  68883. _this._grainTexture = parameters.grain_texture;
  68884. }
  68885. else {
  68886. _this._createGrainTexture();
  68887. }
  68888. // save parameters
  68889. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68890. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68891. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68892. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68893. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68894. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68895. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68896. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68897. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68898. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68899. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68900. // Create effects
  68901. _this._createChromaticAberrationPostProcess(ratio);
  68902. _this._createHighlightsPostProcess(ratio);
  68903. _this._createDepthOfFieldPostProcess(ratio / 4);
  68904. // Set up pipeline
  68905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68907. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68908. if (_this._highlightsGain === -1) {
  68909. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68910. }
  68911. // Finish
  68912. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68913. if (cameras) {
  68914. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68915. }
  68916. return _this;
  68917. }
  68918. // public methods (self explanatory)
  68919. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68920. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68921. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68922. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68923. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68924. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68925. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68926. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68927. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68928. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68929. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68930. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68931. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68932. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68933. };
  68934. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68935. this._highlightsPostProcess.updateEffect();
  68936. };
  68937. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68938. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68939. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68940. this._highlightsGain = amount;
  68941. };
  68942. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68943. if (this._highlightsGain === -1) {
  68944. this._highlightsGain = 1.0;
  68945. }
  68946. this._highlightsThreshold = amount;
  68947. };
  68948. LensRenderingPipeline.prototype.disableHighlights = function () {
  68949. this._highlightsGain = -1;
  68950. };
  68951. /**
  68952. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68953. */
  68954. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68955. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68956. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68957. this._chromaticAberrationPostProcess = null;
  68958. this._highlightsPostProcess = null;
  68959. this._depthOfFieldPostProcess = null;
  68960. this._grainTexture.dispose();
  68961. if (disableDepthRender)
  68962. this._scene.disableDepthRenderer();
  68963. };
  68964. // colors shifting and distortion
  68965. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68966. var _this = this;
  68967. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68968. [], // samplers
  68969. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68970. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68971. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68972. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68973. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68974. effect.setFloat('radialIntensity', 1);
  68975. effect.setFloat2('direction', 17, 17);
  68976. effect.setFloat2('centerPosition', 0.5, 0.5);
  68977. };
  68978. };
  68979. // highlights enhancing
  68980. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68981. var _this = this;
  68982. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68983. [], // samplers
  68984. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68985. this._highlightsPostProcess.onApply = function (effect) {
  68986. effect.setFloat('gain', _this._highlightsGain);
  68987. effect.setFloat('threshold', _this._highlightsThreshold);
  68988. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68989. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68990. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68991. };
  68992. };
  68993. // colors shifting and distortion
  68994. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68995. var _this = this;
  68996. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68997. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68998. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68999. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  69000. this._depthOfFieldPostProcess.onApply = function (effect) {
  69001. effect.setTexture("depthSampler", _this._depthTexture);
  69002. effect.setTexture("grainSampler", _this._grainTexture);
  69003. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  69004. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  69005. effect.setFloat('grain_amount', _this._grainAmount);
  69006. effect.setBool('blur_noise', _this._blurNoise);
  69007. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  69008. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  69009. effect.setFloat('distortion', _this._distortion);
  69010. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  69011. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  69012. effect.setFloat('aperture', _this._dofAperture);
  69013. effect.setFloat('darken', _this._dofDarken);
  69014. effect.setFloat('edge_blur', _this._edgeBlur);
  69015. effect.setBool('highlights', (_this._highlightsGain !== -1));
  69016. if (_this._scene.activeCamera) {
  69017. effect.setFloat('near', _this._scene.activeCamera.minZ);
  69018. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  69019. }
  69020. };
  69021. };
  69022. // creates a black and white random noise texture, 512x512
  69023. LensRenderingPipeline.prototype._createGrainTexture = function () {
  69024. var size = 512;
  69025. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69026. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  69027. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  69028. var context = this._grainTexture.getContext();
  69029. var rand = function (min, max) {
  69030. return Math.random() * (max - min) + min;
  69031. };
  69032. var value;
  69033. for (var x = 0; x < size; x++) {
  69034. for (var y = 0; y < size; y++) {
  69035. value = Math.floor(rand(0.42, 0.58) * 255);
  69036. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  69037. context.fillRect(x, y, 1, 1);
  69038. }
  69039. }
  69040. this._grainTexture.update(false);
  69041. };
  69042. return LensRenderingPipeline;
  69043. }(BABYLON.PostProcessRenderPipeline));
  69044. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  69045. })(BABYLON || (BABYLON = {}));
  69046. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  69047. "use strict";
  69048. var BABYLON;
  69049. (function (BABYLON) {
  69050. var StandardRenderingPipeline = /** @class */ (function (_super) {
  69051. __extends(StandardRenderingPipeline, _super);
  69052. /**
  69053. * @constructor
  69054. * @param {string} name - The rendering pipeline name
  69055. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  69056. * @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)
  69057. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  69058. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  69059. */
  69060. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  69061. if (originalPostProcess === void 0) { originalPostProcess = null; }
  69062. var _this = _super.call(this, scene.getEngine(), name) || this;
  69063. _this.downSampleX4PostProcess = null;
  69064. _this.brightPassPostProcess = null;
  69065. _this.blurHPostProcesses = [];
  69066. _this.blurVPostProcesses = [];
  69067. _this.textureAdderPostProcess = null;
  69068. _this.volumetricLightPostProcess = null;
  69069. _this.volumetricLightSmoothXPostProcess = null;
  69070. _this.volumetricLightSmoothYPostProcess = null;
  69071. _this.volumetricLightMergePostProces = null;
  69072. _this.volumetricLightFinalPostProcess = null;
  69073. _this.luminancePostProcess = null;
  69074. _this.luminanceDownSamplePostProcesses = [];
  69075. _this.hdrPostProcess = null;
  69076. _this.textureAdderFinalPostProcess = null;
  69077. _this.lensFlareFinalPostProcess = null;
  69078. _this.hdrFinalPostProcess = null;
  69079. _this.lensFlarePostProcess = null;
  69080. _this.lensFlareComposePostProcess = null;
  69081. _this.motionBlurPostProcess = null;
  69082. _this.depthOfFieldPostProcess = null;
  69083. // Values
  69084. _this.brightThreshold = 1.0;
  69085. _this.blurWidth = 512.0;
  69086. _this.horizontalBlur = false;
  69087. _this.exposure = 1.0;
  69088. _this.lensTexture = null;
  69089. _this.volumetricLightCoefficient = 0.2;
  69090. _this.volumetricLightPower = 4.0;
  69091. _this.volumetricLightBlurScale = 64.0;
  69092. _this.sourceLight = null;
  69093. _this.hdrMinimumLuminance = 1.0;
  69094. _this.hdrDecreaseRate = 0.5;
  69095. _this.hdrIncreaseRate = 0.5;
  69096. _this.lensColorTexture = null;
  69097. _this.lensFlareStrength = 20.0;
  69098. _this.lensFlareGhostDispersal = 1.4;
  69099. _this.lensFlareHaloWidth = 0.7;
  69100. _this.lensFlareDistortionStrength = 16.0;
  69101. _this.lensStarTexture = null;
  69102. _this.lensFlareDirtTexture = null;
  69103. _this.depthOfFieldDistance = 10.0;
  69104. _this.depthOfFieldBlurWidth = 64.0;
  69105. _this.motionStrength = 1.0;
  69106. // IAnimatable
  69107. _this.animations = [];
  69108. _this._currentDepthOfFieldSource = null;
  69109. _this._hdrCurrentLuminance = 1.0;
  69110. // Getters and setters
  69111. _this._bloomEnabled = true;
  69112. _this._depthOfFieldEnabled = false;
  69113. _this._vlsEnabled = false;
  69114. _this._lensFlareEnabled = false;
  69115. _this._hdrEnabled = false;
  69116. _this._motionBlurEnabled = false;
  69117. _this._motionBlurSamples = 64.0;
  69118. _this._volumetricLightStepsCount = 50.0;
  69119. _this._cameras = cameras || [];
  69120. // Initialize
  69121. _this._scene = scene;
  69122. _this._basePostProcess = originalPostProcess;
  69123. _this._ratio = ratio;
  69124. // Misc
  69125. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69126. // Finish
  69127. scene.postProcessRenderPipelineManager.addPipeline(_this);
  69128. _this._buildPipeline();
  69129. return _this;
  69130. }
  69131. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  69132. get: function () {
  69133. return this._bloomEnabled;
  69134. },
  69135. set: function (enabled) {
  69136. if (this._bloomEnabled === enabled) {
  69137. return;
  69138. }
  69139. this._bloomEnabled = enabled;
  69140. this._buildPipeline();
  69141. },
  69142. enumerable: true,
  69143. configurable: true
  69144. });
  69145. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  69146. get: function () {
  69147. return this._depthOfFieldEnabled;
  69148. },
  69149. set: function (enabled) {
  69150. if (this._depthOfFieldEnabled === enabled) {
  69151. return;
  69152. }
  69153. this._depthOfFieldEnabled = enabled;
  69154. this._buildPipeline();
  69155. },
  69156. enumerable: true,
  69157. configurable: true
  69158. });
  69159. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  69160. get: function () {
  69161. return this._lensFlareEnabled;
  69162. },
  69163. set: function (enabled) {
  69164. if (this._lensFlareEnabled === enabled) {
  69165. return;
  69166. }
  69167. this._lensFlareEnabled = enabled;
  69168. this._buildPipeline();
  69169. },
  69170. enumerable: true,
  69171. configurable: true
  69172. });
  69173. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  69174. get: function () {
  69175. return this._hdrEnabled;
  69176. },
  69177. set: function (enabled) {
  69178. if (this._hdrEnabled === enabled) {
  69179. return;
  69180. }
  69181. this._hdrEnabled = enabled;
  69182. this._buildPipeline();
  69183. },
  69184. enumerable: true,
  69185. configurable: true
  69186. });
  69187. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  69188. get: function () {
  69189. return this._vlsEnabled;
  69190. },
  69191. set: function (enabled) {
  69192. if (this._vlsEnabled === enabled) {
  69193. return;
  69194. }
  69195. if (enabled) {
  69196. var geometry = this._scene.enableGeometryBufferRenderer();
  69197. if (!geometry) {
  69198. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  69199. return;
  69200. }
  69201. }
  69202. this._vlsEnabled = enabled;
  69203. this._buildPipeline();
  69204. },
  69205. enumerable: true,
  69206. configurable: true
  69207. });
  69208. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  69209. get: function () {
  69210. return this._motionBlurEnabled;
  69211. },
  69212. set: function (enabled) {
  69213. if (this._motionBlurEnabled === enabled) {
  69214. return;
  69215. }
  69216. this._motionBlurEnabled = enabled;
  69217. this._buildPipeline();
  69218. },
  69219. enumerable: true,
  69220. configurable: true
  69221. });
  69222. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  69223. get: function () {
  69224. return this._volumetricLightStepsCount;
  69225. },
  69226. set: function (count) {
  69227. if (this.volumetricLightPostProcess) {
  69228. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  69229. }
  69230. this._volumetricLightStepsCount = count;
  69231. },
  69232. enumerable: true,
  69233. configurable: true
  69234. });
  69235. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  69236. get: function () {
  69237. return this._motionBlurSamples;
  69238. },
  69239. set: function (samples) {
  69240. if (this.motionBlurPostProcess) {
  69241. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  69242. }
  69243. this._motionBlurSamples = samples;
  69244. },
  69245. enumerable: true,
  69246. configurable: true
  69247. });
  69248. StandardRenderingPipeline.prototype._buildPipeline = function () {
  69249. var _this = this;
  69250. var ratio = this._ratio;
  69251. var scene = this._scene;
  69252. this._disposePostProcesses();
  69253. this._reset();
  69254. // Create pass post-process
  69255. if (!this._basePostProcess) {
  69256. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  69257. this.originalPostProcess.onApply = function (effect) {
  69258. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  69259. };
  69260. }
  69261. else {
  69262. this.originalPostProcess = this._basePostProcess;
  69263. }
  69264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  69265. this._currentDepthOfFieldSource = this.originalPostProcess;
  69266. if (this._vlsEnabled) {
  69267. // Create volumetric light
  69268. this._createVolumetricLightPostProcess(scene, ratio);
  69269. // Create volumetric light final post-process
  69270. 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);
  69271. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  69272. }
  69273. if (this._bloomEnabled) {
  69274. // Create down sample X4 post-process
  69275. this._createDownSampleX4PostProcess(scene, ratio / 2);
  69276. // Create bright pass post-process
  69277. this._createBrightPassPostProcess(scene, ratio / 2);
  69278. // Create gaussian blur post-processes (down sampling blurs)
  69279. this._createBlurPostProcesses(scene, ratio / 4, 1);
  69280. // Create texture adder post-process
  69281. this._createTextureAdderPostProcess(scene, ratio);
  69282. // Create depth-of-field source post-process
  69283. 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);
  69284. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  69285. }
  69286. if (this._lensFlareEnabled) {
  69287. // Create lens flare post-process
  69288. this._createLensFlarePostProcess(scene, ratio);
  69289. // Create depth-of-field source post-process post lens-flare and disable it now
  69290. 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);
  69291. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  69292. }
  69293. if (this._hdrEnabled) {
  69294. // Create luminance
  69295. this._createLuminancePostProcesses(scene, this._floatTextureType);
  69296. // Create HDR
  69297. this._createHdrPostProcess(scene, ratio);
  69298. // Create depth-of-field source post-process post hdr and disable it now
  69299. 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);
  69300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  69301. }
  69302. if (this._depthOfFieldEnabled) {
  69303. // Create gaussian blur used by depth-of-field
  69304. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  69305. // Create depth-of-field post-process
  69306. this._createDepthOfFieldPostProcess(scene, ratio);
  69307. }
  69308. if (this._motionBlurEnabled) {
  69309. // Create motion blur post-process
  69310. this._createMotionBlurPostProcess(scene, ratio);
  69311. }
  69312. if (this._cameras !== null) {
  69313. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  69314. }
  69315. };
  69316. // Down Sample X4 Post-Processs
  69317. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69318. var _this = this;
  69319. var downSampleX4Offsets = new Array(32);
  69320. 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);
  69321. this.downSampleX4PostProcess.onApply = function (effect) {
  69322. var id = 0;
  69323. var width = _this.downSampleX4PostProcess.width;
  69324. var height = _this.downSampleX4PostProcess.height;
  69325. for (var i = -2; i < 2; i++) {
  69326. for (var j = -2; j < 2; j++) {
  69327. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69328. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69329. id += 2;
  69330. }
  69331. }
  69332. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69333. };
  69334. // Add to pipeline
  69335. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69336. };
  69337. // Brightpass Post-Process
  69338. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69339. var _this = this;
  69340. var brightOffsets = new Array(8);
  69341. 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);
  69342. this.brightPassPostProcess.onApply = function (effect) {
  69343. var sU = (1.0 / _this.brightPassPostProcess.width);
  69344. var sV = (1.0 / _this.brightPassPostProcess.height);
  69345. brightOffsets[0] = -0.5 * sU;
  69346. brightOffsets[1] = 0.5 * sV;
  69347. brightOffsets[2] = 0.5 * sU;
  69348. brightOffsets[3] = 0.5 * sV;
  69349. brightOffsets[4] = -0.5 * sU;
  69350. brightOffsets[5] = -0.5 * sV;
  69351. brightOffsets[6] = 0.5 * sU;
  69352. brightOffsets[7] = -0.5 * sV;
  69353. effect.setArray2("dsOffsets", brightOffsets);
  69354. effect.setFloat("brightThreshold", _this.brightThreshold);
  69355. };
  69356. // Add to pipeline
  69357. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69358. };
  69359. // Create blur H&V post-processes
  69360. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69361. var _this = this;
  69362. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69363. var engine = scene.getEngine();
  69364. 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);
  69365. 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);
  69366. blurX.onActivateObservable.add(function () {
  69367. var dw = blurX.width / engine.getRenderWidth();
  69368. blurX.kernel = _this[blurWidthKey] * dw;
  69369. });
  69370. blurY.onActivateObservable.add(function () {
  69371. var dw = blurY.height / engine.getRenderHeight();
  69372. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69373. });
  69374. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69375. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69376. this.blurHPostProcesses.push(blurX);
  69377. this.blurVPostProcesses.push(blurY);
  69378. };
  69379. // Create texture adder post-process
  69380. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69381. var _this = this;
  69382. 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);
  69383. this.textureAdderPostProcess.onApply = function (effect) {
  69384. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69385. effect.setTexture("lensSampler", _this.lensTexture);
  69386. effect.setFloat("exposure", _this.exposure);
  69387. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69388. };
  69389. // Add to pipeline
  69390. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69391. };
  69392. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69393. var _this = this;
  69394. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69395. geometryRenderer.enablePosition = true;
  69396. var geometry = geometryRenderer.getGBuffer();
  69397. // Base post-process
  69398. 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));
  69399. var depthValues = BABYLON.Vector2.Zero();
  69400. this.volumetricLightPostProcess.onApply = function (effect) {
  69401. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69402. var generator = _this.sourceLight.getShadowGenerator();
  69403. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69404. effect.setTexture("positionSampler", geometry.textures[2]);
  69405. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69406. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69407. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69408. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69409. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69410. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69411. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69412. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69413. effect.setVector2("depthValues", depthValues);
  69414. }
  69415. };
  69416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69417. // Smooth
  69418. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69419. // Merge
  69420. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69421. this.volumetricLightMergePostProces.onApply = function (effect) {
  69422. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69423. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69424. };
  69425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69426. };
  69427. // Create luminance
  69428. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69429. var _this = this;
  69430. // Create luminance
  69431. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69432. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69433. var offsets = [];
  69434. this.luminancePostProcess.onApply = function (effect) {
  69435. var sU = (1.0 / _this.luminancePostProcess.width);
  69436. var sV = (1.0 / _this.luminancePostProcess.height);
  69437. offsets[0] = -0.5 * sU;
  69438. offsets[1] = 0.5 * sV;
  69439. offsets[2] = 0.5 * sU;
  69440. offsets[3] = 0.5 * sV;
  69441. offsets[4] = -0.5 * sU;
  69442. offsets[5] = -0.5 * sV;
  69443. offsets[6] = 0.5 * sU;
  69444. offsets[7] = -0.5 * sV;
  69445. effect.setArray2("lumOffsets", offsets);
  69446. };
  69447. // Add to pipeline
  69448. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69449. // Create down sample luminance
  69450. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69451. var size = Math.pow(3, i);
  69452. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69453. if (i === 0) {
  69454. defines += "#define FINAL_DOWN_SAMPLER";
  69455. }
  69456. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69457. this.luminanceDownSamplePostProcesses.push(postProcess);
  69458. }
  69459. // Create callbacks and add effects
  69460. var lastLuminance = this.luminancePostProcess;
  69461. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69462. var downSampleOffsets = new Array(18);
  69463. pp.onApply = function (effect) {
  69464. if (!lastLuminance) {
  69465. return;
  69466. }
  69467. var id = 0;
  69468. for (var x = -1; x < 2; x++) {
  69469. for (var y = -1; y < 2; y++) {
  69470. downSampleOffsets[id] = x / lastLuminance.width;
  69471. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69472. id += 2;
  69473. }
  69474. }
  69475. effect.setArray2("dsOffsets", downSampleOffsets);
  69476. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69477. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69478. lastLuminance = _this.luminancePostProcess;
  69479. }
  69480. else {
  69481. lastLuminance = pp;
  69482. }
  69483. };
  69484. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69485. pp.onAfterRender = function (effect) {
  69486. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69487. 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);
  69488. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69489. };
  69490. }
  69491. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69492. });
  69493. };
  69494. // Create HDR post-process
  69495. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69496. var _this = this;
  69497. 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);
  69498. var outputLiminance = 1;
  69499. var time = 0;
  69500. var lastTime = 0;
  69501. this.hdrPostProcess.onApply = function (effect) {
  69502. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69503. time += scene.getEngine().getDeltaTime();
  69504. if (outputLiminance < 0) {
  69505. outputLiminance = _this._hdrCurrentLuminance;
  69506. }
  69507. else {
  69508. var dt = (lastTime - time) / 1000.0;
  69509. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69510. outputLiminance += _this.hdrDecreaseRate * dt;
  69511. }
  69512. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69513. outputLiminance -= _this.hdrIncreaseRate * dt;
  69514. }
  69515. else {
  69516. outputLiminance = _this._hdrCurrentLuminance;
  69517. }
  69518. }
  69519. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69520. effect.setFloat("averageLuminance", outputLiminance);
  69521. lastTime = time;
  69522. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69523. };
  69524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69525. };
  69526. // Create lens flare post-process
  69527. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69528. var _this = this;
  69529. 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);
  69530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69531. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69532. 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);
  69533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69534. var resolution = new BABYLON.Vector2(0, 0);
  69535. // Lens flare
  69536. this.lensFlarePostProcess.onApply = function (effect) {
  69537. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69538. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69539. effect.setFloat("strength", _this.lensFlareStrength);
  69540. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69541. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69542. // Shift
  69543. resolution.x = _this.lensFlarePostProcess.width;
  69544. resolution.y = _this.lensFlarePostProcess.height;
  69545. effect.setVector2("resolution", resolution);
  69546. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69547. };
  69548. // Compose
  69549. 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);
  69550. 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);
  69551. this.lensFlareComposePostProcess.onApply = function (effect) {
  69552. if (!_this._scene.activeCamera) {
  69553. return;
  69554. }
  69555. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69556. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69557. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69558. // Lens start rotation matrix
  69559. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69560. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69561. 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));
  69562. camRot *= 4.0;
  69563. 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);
  69564. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69565. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69566. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69567. };
  69568. };
  69569. // Create depth-of-field post-process
  69570. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69571. var _this = this;
  69572. 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);
  69573. this.depthOfFieldPostProcess.onApply = function (effect) {
  69574. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69575. effect.setTexture("depthSampler", _this._getDepthTexture());
  69576. effect.setFloat("distance", _this.depthOfFieldDistance);
  69577. };
  69578. // Add to pipeline
  69579. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69580. };
  69581. // Create motion blur post-process
  69582. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69583. var _this = this;
  69584. 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);
  69585. var motionScale = 0;
  69586. var prevViewProjection = BABYLON.Matrix.Identity();
  69587. var invViewProjection = BABYLON.Matrix.Identity();
  69588. var viewProjection = BABYLON.Matrix.Identity();
  69589. var screenSize = BABYLON.Vector2.Zero();
  69590. this.motionBlurPostProcess.onApply = function (effect) {
  69591. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69592. viewProjection.invertToRef(invViewProjection);
  69593. effect.setMatrix("inverseViewProjection", invViewProjection);
  69594. effect.setMatrix("prevViewProjection", prevViewProjection);
  69595. prevViewProjection = viewProjection;
  69596. screenSize.x = _this.motionBlurPostProcess.width;
  69597. screenSize.y = _this.motionBlurPostProcess.height;
  69598. effect.setVector2("screenSize", screenSize);
  69599. motionScale = scene.getEngine().getFps() / 60.0;
  69600. effect.setFloat("motionScale", motionScale);
  69601. effect.setFloat("motionStrength", _this.motionStrength);
  69602. effect.setTexture("depthSampler", _this._getDepthTexture());
  69603. };
  69604. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69605. };
  69606. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69607. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69608. var renderer = this._scene.enableGeometryBufferRenderer();
  69609. return renderer.getGBuffer().textures[0];
  69610. }
  69611. return this._scene.enableDepthRenderer().getDepthMap();
  69612. };
  69613. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69614. for (var i = 0; i < this._cameras.length; i++) {
  69615. var camera = this._cameras[i];
  69616. if (this.originalPostProcess) {
  69617. this.originalPostProcess.dispose(camera);
  69618. }
  69619. if (this.downSampleX4PostProcess) {
  69620. this.downSampleX4PostProcess.dispose(camera);
  69621. }
  69622. if (this.brightPassPostProcess) {
  69623. this.brightPassPostProcess.dispose(camera);
  69624. }
  69625. if (this.textureAdderPostProcess) {
  69626. this.textureAdderPostProcess.dispose(camera);
  69627. }
  69628. if (this.textureAdderFinalPostProcess) {
  69629. this.textureAdderFinalPostProcess.dispose(camera);
  69630. }
  69631. if (this.volumetricLightPostProcess) {
  69632. this.volumetricLightPostProcess.dispose(camera);
  69633. }
  69634. if (this.volumetricLightSmoothXPostProcess) {
  69635. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69636. }
  69637. if (this.volumetricLightSmoothYPostProcess) {
  69638. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69639. }
  69640. if (this.volumetricLightMergePostProces) {
  69641. this.volumetricLightMergePostProces.dispose(camera);
  69642. }
  69643. if (this.volumetricLightFinalPostProcess) {
  69644. this.volumetricLightFinalPostProcess.dispose(camera);
  69645. }
  69646. if (this.lensFlarePostProcess) {
  69647. this.lensFlarePostProcess.dispose(camera);
  69648. }
  69649. if (this.lensFlareComposePostProcess) {
  69650. this.lensFlareComposePostProcess.dispose(camera);
  69651. }
  69652. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69653. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69654. }
  69655. if (this.luminancePostProcess) {
  69656. this.luminancePostProcess.dispose(camera);
  69657. }
  69658. if (this.hdrPostProcess) {
  69659. this.hdrPostProcess.dispose(camera);
  69660. }
  69661. if (this.hdrFinalPostProcess) {
  69662. this.hdrFinalPostProcess.dispose(camera);
  69663. }
  69664. if (this.depthOfFieldPostProcess) {
  69665. this.depthOfFieldPostProcess.dispose(camera);
  69666. }
  69667. if (this.motionBlurPostProcess) {
  69668. this.motionBlurPostProcess.dispose(camera);
  69669. }
  69670. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69671. this.blurHPostProcesses[j].dispose(camera);
  69672. }
  69673. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69674. this.blurVPostProcesses[j].dispose(camera);
  69675. }
  69676. }
  69677. this.originalPostProcess = null;
  69678. this.downSampleX4PostProcess = null;
  69679. this.brightPassPostProcess = null;
  69680. this.textureAdderPostProcess = null;
  69681. this.textureAdderFinalPostProcess = null;
  69682. this.volumetricLightPostProcess = null;
  69683. this.volumetricLightSmoothXPostProcess = null;
  69684. this.volumetricLightSmoothYPostProcess = null;
  69685. this.volumetricLightMergePostProces = null;
  69686. this.volumetricLightFinalPostProcess = null;
  69687. this.lensFlarePostProcess = null;
  69688. this.lensFlareComposePostProcess = null;
  69689. this.luminancePostProcess = null;
  69690. this.hdrPostProcess = null;
  69691. this.hdrFinalPostProcess = null;
  69692. this.depthOfFieldPostProcess = null;
  69693. this.motionBlurPostProcess = null;
  69694. this.luminanceDownSamplePostProcesses = [];
  69695. this.blurHPostProcesses = [];
  69696. this.blurVPostProcesses = [];
  69697. };
  69698. // Dispose
  69699. StandardRenderingPipeline.prototype.dispose = function () {
  69700. this._disposePostProcesses();
  69701. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69702. _super.prototype.dispose.call(this);
  69703. };
  69704. // Serialize rendering pipeline
  69705. StandardRenderingPipeline.prototype.serialize = function () {
  69706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69707. serializationObject.customType = "StandardRenderingPipeline";
  69708. return serializationObject;
  69709. };
  69710. /**
  69711. * Static members
  69712. */
  69713. // Parse serialized pipeline
  69714. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69715. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69716. };
  69717. // Luminance steps
  69718. StandardRenderingPipeline.LuminanceSteps = 6;
  69719. __decorate([
  69720. BABYLON.serialize()
  69721. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69722. __decorate([
  69723. BABYLON.serialize()
  69724. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69725. __decorate([
  69726. BABYLON.serialize()
  69727. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69728. __decorate([
  69729. BABYLON.serialize()
  69730. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69731. __decorate([
  69732. BABYLON.serializeAsTexture("lensTexture")
  69733. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69734. __decorate([
  69735. BABYLON.serialize()
  69736. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69737. __decorate([
  69738. BABYLON.serialize()
  69739. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69740. __decorate([
  69741. BABYLON.serialize()
  69742. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69743. __decorate([
  69744. BABYLON.serialize()
  69745. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69746. __decorate([
  69747. BABYLON.serialize()
  69748. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69749. __decorate([
  69750. BABYLON.serialize()
  69751. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69752. __decorate([
  69753. BABYLON.serializeAsTexture("lensColorTexture")
  69754. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69755. __decorate([
  69756. BABYLON.serialize()
  69757. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69758. __decorate([
  69759. BABYLON.serialize()
  69760. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69761. __decorate([
  69762. BABYLON.serialize()
  69763. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69764. __decorate([
  69765. BABYLON.serialize()
  69766. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69767. __decorate([
  69768. BABYLON.serializeAsTexture("lensStarTexture")
  69769. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69770. __decorate([
  69771. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69772. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69773. __decorate([
  69774. BABYLON.serialize()
  69775. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69776. __decorate([
  69777. BABYLON.serialize()
  69778. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69779. __decorate([
  69780. BABYLON.serialize()
  69781. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69782. __decorate([
  69783. BABYLON.serialize()
  69784. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69785. __decorate([
  69786. BABYLON.serialize()
  69787. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69788. __decorate([
  69789. BABYLON.serialize()
  69790. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69791. __decorate([
  69792. BABYLON.serialize()
  69793. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69794. __decorate([
  69795. BABYLON.serialize()
  69796. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69797. __decorate([
  69798. BABYLON.serialize()
  69799. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69800. __decorate([
  69801. BABYLON.serialize()
  69802. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69803. __decorate([
  69804. BABYLON.serialize()
  69805. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69806. __decorate([
  69807. BABYLON.serialize()
  69808. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69809. return StandardRenderingPipeline;
  69810. }(BABYLON.PostProcessRenderPipeline));
  69811. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69812. })(BABYLON || (BABYLON = {}));
  69813. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69814. "use strict";
  69815. var BABYLON;
  69816. (function (BABYLON) {
  69817. var FxaaPostProcess = /** @class */ (function (_super) {
  69818. __extends(FxaaPostProcess, _super);
  69819. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69820. if (camera === void 0) { camera = null; }
  69821. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69822. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69823. _this.onApplyObservable.add(function (effect) {
  69824. var texelSize = _this.texelSize;
  69825. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69826. });
  69827. return _this;
  69828. }
  69829. return FxaaPostProcess;
  69830. }(BABYLON.PostProcess));
  69831. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69832. })(BABYLON || (BABYLON = {}));
  69833. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69834. "use strict";
  69835. var BABYLON;
  69836. (function (BABYLON) {
  69837. /**
  69838. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69839. */
  69840. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69841. __extends(ChromaticAberrationPostProcess, _super);
  69842. /**
  69843. * Creates a new instance ChromaticAberrationPostProcess
  69844. * @param name The name of the effect.
  69845. * @param screenWidth The width of the screen to apply the effect on.
  69846. * @param screenHeight The height of the screen to apply the effect on.
  69847. * @param options The required width/height ratio to downsize to before computing the render pass.
  69848. * @param camera The camera to apply the render pass to.
  69849. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69850. * @param engine The engine which the post process will be applied. (default: current engine)
  69851. * @param reusable If the post process can be reused on the same frame. (default: false)
  69852. * @param textureType Type of textures used when performing the post process. (default: 0)
  69853. * @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)
  69854. */
  69855. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69856. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69857. if (blockCompilation === void 0) { blockCompilation = false; }
  69858. 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;
  69859. /**
  69860. * The amount of seperation of rgb channels (default: 30)
  69861. */
  69862. _this.aberrationAmount = 30;
  69863. /**
  69864. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69865. */
  69866. _this.radialIntensity = 0;
  69867. /**
  69868. * 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))
  69869. */
  69870. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69871. /**
  69872. * 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))
  69873. */
  69874. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69875. _this.onApplyObservable.add(function (effect) {
  69876. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69877. effect.setFloat('screen_width', screenWidth);
  69878. effect.setFloat('screen_height', screenHeight);
  69879. effect.setFloat('radialIntensity', _this.radialIntensity);
  69880. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69881. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69882. });
  69883. return _this;
  69884. }
  69885. return ChromaticAberrationPostProcess;
  69886. }(BABYLON.PostProcess));
  69887. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69888. })(BABYLON || (BABYLON = {}));
  69889. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69890. "use strict";
  69891. var BABYLON;
  69892. (function (BABYLON) {
  69893. /**
  69894. * The GrainPostProcess adds noise to the image at mid luminance levels
  69895. */
  69896. var GrainPostProcess = /** @class */ (function (_super) {
  69897. __extends(GrainPostProcess, _super);
  69898. /**
  69899. * Creates a new instance of @see GrainPostProcess
  69900. * @param name The name of the effect.
  69901. * @param options The required width/height ratio to downsize to before computing the render pass.
  69902. * @param camera The camera to apply the render pass to.
  69903. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69904. * @param engine The engine which the post process will be applied. (default: current engine)
  69905. * @param reusable If the post process can be reused on the same frame. (default: false)
  69906. * @param textureType Type of textures used when performing the post process. (default: 0)
  69907. * @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)
  69908. */
  69909. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69910. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69911. if (blockCompilation === void 0) { blockCompilation = false; }
  69912. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69913. /**
  69914. * The intensity of the grain added (default: 30)
  69915. */
  69916. _this.intensity = 30;
  69917. /**
  69918. * If the grain should be randomized on every frame
  69919. */
  69920. _this.animated = false;
  69921. _this.onApplyObservable.add(function (effect) {
  69922. effect.setFloat('intensity', _this.intensity);
  69923. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  69924. });
  69925. return _this;
  69926. }
  69927. return GrainPostProcess;
  69928. }(BABYLON.PostProcess));
  69929. BABYLON.GrainPostProcess = GrainPostProcess;
  69930. })(BABYLON || (BABYLON = {}));
  69931. //# sourceMappingURL=babylon.grainPostProcess.js.map
  69932. "use strict";
  69933. var BABYLON;
  69934. (function (BABYLON) {
  69935. /**
  69936. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69937. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69938. */
  69939. var SharpenPostProcess = /** @class */ (function (_super) {
  69940. __extends(SharpenPostProcess, _super);
  69941. /**
  69942. * Creates a new instance ConvolutionPostProcess
  69943. * @param name The name of the effect.
  69944. * @param options The required width/height ratio to downsize to before computing the render pass.
  69945. * @param camera The camera to apply the render pass to.
  69946. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69947. * @param engine The engine which the post process will be applied. (default: current engine)
  69948. * @param reusable If the post process can be reused on the same frame. (default: false)
  69949. * @param textureType Type of textures used when performing the post process. (default: 0)
  69950. * @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)
  69951. */
  69952. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69953. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69954. if (blockCompilation === void 0) { blockCompilation = false; }
  69955. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69956. /**
  69957. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69958. */
  69959. _this.colorAmount = 1.0;
  69960. /**
  69961. * How much sharpness should be applied (default: 0.3)
  69962. */
  69963. _this.edgeAmount = 0.3;
  69964. _this.onApply = function (effect) {
  69965. effect.setFloat2("screenSize", _this.width, _this.height);
  69966. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69967. };
  69968. return _this;
  69969. }
  69970. return SharpenPostProcess;
  69971. }(BABYLON.PostProcess));
  69972. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69973. })(BABYLON || (BABYLON = {}));
  69974. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69975. "use strict";
  69976. var BABYLON;
  69977. (function (BABYLON) {
  69978. /**
  69979. * The Blur Post Process which blurs an image based on a kernel and direction.
  69980. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69981. */
  69982. var BlurPostProcess = /** @class */ (function (_super) {
  69983. __extends(BlurPostProcess, _super);
  69984. /**
  69985. * Creates a new instance BlurPostProcess
  69986. * @param name The name of the effect.
  69987. * @param direction The direction in which to blur the image.
  69988. * @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.
  69989. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69990. * @param camera The camera to apply the render pass to.
  69991. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69992. * @param engine The engine which the post process will be applied. (default: current engine)
  69993. * @param reusable If the post process can be reused on the same frame. (default: false)
  69994. * @param textureType Type of textures used when performing the post process. (default: 0)
  69995. * @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)
  69996. */
  69997. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69999. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70000. if (defines === void 0) { defines = ""; }
  70001. if (blockCompilation === void 0) { blockCompilation = false; }
  70002. 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;
  70003. _this.direction = direction;
  70004. _this.blockCompilation = blockCompilation;
  70005. _this._packedFloat = false;
  70006. _this._staticDefines = "";
  70007. _this._staticDefines = defines;
  70008. _this.onApplyObservable.add(function (effect) {
  70009. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  70010. });
  70011. _this.kernel = kernel;
  70012. return _this;
  70013. }
  70014. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  70015. /**
  70016. * Gets the length in pixels of the blur sample region
  70017. */
  70018. get: function () {
  70019. return this._idealKernel;
  70020. },
  70021. /**
  70022. * Sets the length in pixels of the blur sample region
  70023. */
  70024. set: function (v) {
  70025. if (this._idealKernel === v) {
  70026. return;
  70027. }
  70028. v = Math.max(v, 1);
  70029. this._idealKernel = v;
  70030. this._kernel = this._nearestBestKernel(v);
  70031. if (!this.blockCompilation) {
  70032. this._updateParameters();
  70033. }
  70034. },
  70035. enumerable: true,
  70036. configurable: true
  70037. });
  70038. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  70039. /**
  70040. * Gets wether or not the blur is unpacking/repacking floats
  70041. */
  70042. get: function () {
  70043. return this._packedFloat;
  70044. },
  70045. /**
  70046. * Sets wether or not the blur needs to unpack/repack floats
  70047. */
  70048. set: function (v) {
  70049. if (this._packedFloat === v) {
  70050. return;
  70051. }
  70052. this._packedFloat = v;
  70053. if (!this.blockCompilation) {
  70054. this._updateParameters();
  70055. }
  70056. },
  70057. enumerable: true,
  70058. configurable: true
  70059. });
  70060. /**
  70061. * Updates the effect with the current post process compile time values and recompiles the shader.
  70062. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70063. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70064. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70065. * @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
  70066. * @param onCompiled Called when the shader has been compiled.
  70067. * @param onError Called if there is an error when compiling a shader.
  70068. */
  70069. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70070. if (defines === void 0) { defines = null; }
  70071. if (uniforms === void 0) { uniforms = null; }
  70072. if (samplers === void 0) { samplers = null; }
  70073. this._updateParameters(onCompiled, onError);
  70074. };
  70075. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  70076. // Generate sampling offsets and weights
  70077. var N = this._kernel;
  70078. var centerIndex = (N - 1) / 2;
  70079. // Generate Gaussian sampling weights over kernel
  70080. var offsets = [];
  70081. var weights = [];
  70082. var totalWeight = 0;
  70083. for (var i = 0; i < N; i++) {
  70084. var u = i / (N - 1);
  70085. var w = this._gaussianWeight(u * 2.0 - 1);
  70086. offsets[i] = (i - centerIndex);
  70087. weights[i] = w;
  70088. totalWeight += w;
  70089. }
  70090. // Normalize weights
  70091. for (var i = 0; i < weights.length; i++) {
  70092. weights[i] /= totalWeight;
  70093. }
  70094. // Optimize: combine samples to take advantage of hardware linear sampling
  70095. // Walk from left to center, combining pairs (symmetrically)
  70096. var linearSamplingWeights = [];
  70097. var linearSamplingOffsets = [];
  70098. var linearSamplingMap = [];
  70099. for (var i = 0; i <= centerIndex; i += 2) {
  70100. var j = Math.min(i + 1, Math.floor(centerIndex));
  70101. var singleCenterSample = i === j;
  70102. if (singleCenterSample) {
  70103. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70104. }
  70105. else {
  70106. var sharedCell = j === centerIndex;
  70107. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  70108. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  70109. if (offsetLinear === 0) {
  70110. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  70111. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  70112. }
  70113. else {
  70114. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  70115. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  70116. }
  70117. }
  70118. }
  70119. for (var i = 0; i < linearSamplingMap.length; i++) {
  70120. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  70121. linearSamplingWeights[i] = linearSamplingMap[i].w;
  70122. }
  70123. // Replace with optimized
  70124. offsets = linearSamplingOffsets;
  70125. weights = linearSamplingWeights;
  70126. // Generate shaders
  70127. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  70128. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  70129. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  70130. var defines = "";
  70131. defines += this._staticDefines;
  70132. for (var i = 0; i < varyingCount; i++) {
  70133. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  70134. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  70135. }
  70136. var depCount = 0;
  70137. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  70138. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  70139. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  70140. depCount++;
  70141. }
  70142. if (this.packedFloat) {
  70143. defines += "#define PACKEDFLOAT 1";
  70144. }
  70145. this.blockCompilation = false;
  70146. _super.prototype.updateEffect.call(this, defines, null, null, {
  70147. varyingCount: varyingCount,
  70148. depCount: depCount
  70149. }, onCompiled, onError);
  70150. };
  70151. /**
  70152. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  70153. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  70154. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  70155. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  70156. * The gaps between physical kernels are compensated for in the weighting of the samples
  70157. * @param idealKernel Ideal blur kernel.
  70158. * @return Nearest best kernel.
  70159. */
  70160. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  70161. var v = Math.round(idealKernel);
  70162. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  70163. var k = _a[_i];
  70164. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  70165. return Math.max(k, 3);
  70166. }
  70167. }
  70168. return Math.max(v, 3);
  70169. };
  70170. /**
  70171. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  70172. * @param x The point on the Gaussian distribution to sample.
  70173. * @return the value of the Gaussian function at x.
  70174. */
  70175. BlurPostProcess.prototype._gaussianWeight = function (x) {
  70176. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  70177. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  70178. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  70179. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  70180. // truncated at around 1.3% of peak strength.
  70181. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  70182. var sigma = (1 / 3);
  70183. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  70184. var exponent = -((x * x) / (2.0 * sigma * sigma));
  70185. var weight = (1.0 / denominator) * Math.exp(exponent);
  70186. return weight;
  70187. };
  70188. /**
  70189. * Generates a string that can be used as a floating point number in GLSL.
  70190. * @param x Value to print.
  70191. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  70192. * @return GLSL float string.
  70193. */
  70194. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  70195. if (decimalFigures === void 0) { decimalFigures = 8; }
  70196. return x.toFixed(decimalFigures).replace(/0+$/, '');
  70197. };
  70198. return BlurPostProcess;
  70199. }(BABYLON.PostProcess));
  70200. BABYLON.BlurPostProcess = BlurPostProcess;
  70201. })(BABYLON || (BABYLON = {}));
  70202. //# sourceMappingURL=babylon.blurPostProcess.js.map
  70203. "use strict";
  70204. var BABYLON;
  70205. (function (BABYLON) {
  70206. /**
  70207. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  70208. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  70209. * based on samples that have a large difference in distance than the center pixel.
  70210. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70211. */
  70212. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  70213. __extends(DepthOfFieldBlurPostProcess, _super);
  70214. /**
  70215. * Creates a new instance CircleOfConfusionPostProcess
  70216. * @param name The name of the effect.
  70217. * @param scene The scene the effect belongs to.
  70218. * @param direction The direction the blur should be applied.
  70219. * @param kernel The size of the kernel used to blur.
  70220. * @param options The required width/height ratio to downsize to before computing the render pass.
  70221. * @param camera The camera to apply the render pass to.
  70222. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  70223. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  70224. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70225. * @param engine The engine which the post process will be applied. (default: current engine)
  70226. * @param reusable If the post process can be reused on the same frame. (default: false)
  70227. * @param textureType Type of textures used when performing the post process. (default: 0)
  70228. * @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)
  70229. */
  70230. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  70231. if (imageToBlur === void 0) { imageToBlur = null; }
  70232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  70233. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70234. if (blockCompilation === void 0) { blockCompilation = false; }
  70235. 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;
  70236. _this.direction = direction;
  70237. _this.onApplyObservable.add(function (effect) {
  70238. if (imageToBlur != null) {
  70239. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  70240. }
  70241. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70242. if (scene.activeCamera) {
  70243. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  70244. }
  70245. });
  70246. return _this;
  70247. }
  70248. return DepthOfFieldBlurPostProcess;
  70249. }(BABYLON.BlurPostProcess));
  70250. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  70251. })(BABYLON || (BABYLON = {}));
  70252. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  70253. "use strict";
  70254. var BABYLON;
  70255. (function (BABYLON) {
  70256. /**
  70257. * Options to be set when merging outputs from the default pipeline.
  70258. */
  70259. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  70260. function DepthOfFieldMergePostProcessOptions() {
  70261. }
  70262. return DepthOfFieldMergePostProcessOptions;
  70263. }());
  70264. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  70265. /**
  70266. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70267. */
  70268. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  70269. __extends(DepthOfFieldMergePostProcess, _super);
  70270. /**
  70271. <<<<<<< HEAD
  70272. * Creates a new instance CircleOfConfusionPostProcess
  70273. =======
  70274. * Creates a new instance of @see DepthOfFieldMergePostProcess
  70275. >>>>>>> 70d3435c5f934f0416dfbf106f59fe53aacc8393
  70276. * @param name The name of the effect.
  70277. * @param originalFromInput Post process which's input will be used for the merge.
  70278. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  70279. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  70280. * @param options The required width/height ratio to downsize to before computing the render pass.
  70281. * @param camera The camera to apply the render pass to.
  70282. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70283. * @param engine The engine which the post process will be applied. (default: current engine)
  70284. * @param reusable If the post process can be reused on the same frame. (default: false)
  70285. * @param textureType Type of textures used when performing the post process. (default: 0)
  70286. * @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)
  70287. */
  70288. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70289. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70290. if (blockCompilation === void 0) { blockCompilation = false; }
  70291. var _this = _super.call(this, name, "depthOfFieldMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70292. _this.blurSteps = blurSteps;
  70293. _this.onApplyObservable.add(function (effect) {
  70294. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70295. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  70296. blurSteps.forEach(function (step, index) {
  70297. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  70298. });
  70299. });
  70300. if (!blockCompilation) {
  70301. _this.updateEffect();
  70302. }
  70303. return _this;
  70304. }
  70305. /**
  70306. * Updates the effect with the current post process compile time values and recompiles the shader.
  70307. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  70308. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  70309. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  70310. * @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
  70311. * @param onCompiled Called when the shader has been compiled.
  70312. * @param onError Called if there is an error when compiling a shader.
  70313. */
  70314. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  70315. if (defines === void 0) { defines = null; }
  70316. if (uniforms === void 0) { uniforms = null; }
  70317. if (samplers === void 0) { samplers = null; }
  70318. if (!defines) {
  70319. defines = "";
  70320. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  70321. }
  70322. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  70323. };
  70324. return DepthOfFieldMergePostProcess;
  70325. }(BABYLON.PostProcess));
  70326. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  70327. })(BABYLON || (BABYLON = {}));
  70328. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  70329. "use strict";
  70330. var BABYLON;
  70331. (function (BABYLON) {
  70332. /**
  70333. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  70334. */
  70335. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  70336. __extends(CircleOfConfusionPostProcess, _super);
  70337. /**
  70338. * Creates a new instance CircleOfConfusionPostProcess
  70339. * @param name The name of the effect.
  70340. * @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.
  70341. * @param options The required width/height ratio to downsize to before computing the render pass.
  70342. * @param camera The camera to apply the render pass to.
  70343. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70344. * @param engine The engine which the post process will be applied. (default: current engine)
  70345. * @param reusable If the post process can be reused on the same frame. (default: false)
  70346. * @param textureType Type of textures used when performing the post process. (default: 0)
  70347. * @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)
  70348. */
  70349. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70350. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70351. if (blockCompilation === void 0) { blockCompilation = false; }
  70352. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70353. /**
  70354. * 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.
  70355. */
  70356. _this.lensSize = 50;
  70357. /**
  70358. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70359. */
  70360. _this.fStop = 1.4;
  70361. /**
  70362. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70363. */
  70364. _this.focusDistance = 2000;
  70365. /**
  70366. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  70367. */
  70368. _this.focalLength = 50;
  70369. _this._depthTexture = null;
  70370. _this._depthTexture = depthTexture;
  70371. _this.onApplyObservable.add(function (effect) {
  70372. if (!_this._depthTexture) {
  70373. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  70374. return;
  70375. }
  70376. effect.setTexture("depthSampler", _this._depthTexture);
  70377. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70378. var aperture = _this.lensSize / _this.fStop;
  70379. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70380. effect.setFloat('focusDistance', _this.focusDistance);
  70381. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70382. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70383. });
  70384. return _this;
  70385. }
  70386. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70387. /**
  70388. * 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.
  70389. */
  70390. set: function (value) {
  70391. this._depthTexture = value;
  70392. },
  70393. enumerable: true,
  70394. configurable: true
  70395. });
  70396. return CircleOfConfusionPostProcess;
  70397. }(BABYLON.PostProcess));
  70398. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70399. })(BABYLON || (BABYLON = {}));
  70400. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70401. "use strict";
  70402. var BABYLON;
  70403. (function (BABYLON) {
  70404. /**
  70405. * Specifies the level of max blur that should be applied when using the depth of field effect
  70406. */
  70407. var DepthOfFieldEffectBlurLevel;
  70408. (function (DepthOfFieldEffectBlurLevel) {
  70409. /**
  70410. * Subtle blur
  70411. */
  70412. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70413. /**
  70414. * Medium blur
  70415. */
  70416. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70417. /**
  70418. * Large blur
  70419. */
  70420. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70421. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70422. ;
  70423. /**
  70424. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70425. */
  70426. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70427. __extends(DepthOfFieldEffect, _super);
  70428. /**
  70429. * Creates a new instance DepthOfFieldEffect
  70430. * @param scene The scene the effect belongs to.
  70431. * @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.
  70432. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70433. * @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)
  70434. */
  70435. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70436. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70437. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70438. if (blockCompilation === void 0) { blockCompilation = false; }
  70439. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70440. return _this._effects;
  70441. }, true) || this;
  70442. /**
  70443. * Internal post processes in depth of field effect
  70444. */
  70445. _this._effects = [];
  70446. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70447. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70448. // 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)
  70449. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70450. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70451. _this._depthOfFieldBlurY = [];
  70452. _this._depthOfFieldBlurX = [];
  70453. var blurCount = 1;
  70454. var kernelSize = 15;
  70455. switch (blurLevel) {
  70456. case DepthOfFieldEffectBlurLevel.High: {
  70457. blurCount = 3;
  70458. kernelSize = 51;
  70459. break;
  70460. }
  70461. case DepthOfFieldEffectBlurLevel.Medium: {
  70462. blurCount = 2;
  70463. kernelSize = 31;
  70464. break;
  70465. }
  70466. default: {
  70467. kernelSize = 15;
  70468. blurCount = 1;
  70469. break;
  70470. }
  70471. }
  70472. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70473. for (var i = 0; i < blurCount; i++) {
  70474. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70475. blurY.autoClear = false;
  70476. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70477. blurX.autoClear = false;
  70478. _this._depthOfFieldBlurY.push(blurY);
  70479. _this._depthOfFieldBlurX.push(blurX);
  70480. }
  70481. // Set all post processes on the effect.
  70482. _this._effects = [_this._circleOfConfusion];
  70483. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70484. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70485. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70486. }
  70487. // Merge blurred images with original image based on circleOfConfusion
  70488. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70489. _this._dofMerge.autoClear = false;
  70490. _this._effects.push(_this._dofMerge);
  70491. return _this;
  70492. }
  70493. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70494. get: function () {
  70495. return this._circleOfConfusion.focalLength;
  70496. },
  70497. /**
  70498. * The focal the length of the camera used in the effect
  70499. */
  70500. set: function (value) {
  70501. this._circleOfConfusion.focalLength = value;
  70502. },
  70503. enumerable: true,
  70504. configurable: true
  70505. });
  70506. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70507. get: function () {
  70508. return this._circleOfConfusion.fStop;
  70509. },
  70510. /**
  70511. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70512. */
  70513. set: function (value) {
  70514. this._circleOfConfusion.fStop = value;
  70515. },
  70516. enumerable: true,
  70517. configurable: true
  70518. });
  70519. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70520. get: function () {
  70521. return this._circleOfConfusion.focusDistance;
  70522. },
  70523. /**
  70524. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70525. */
  70526. set: function (value) {
  70527. this._circleOfConfusion.focusDistance = value;
  70528. },
  70529. enumerable: true,
  70530. configurable: true
  70531. });
  70532. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70533. get: function () {
  70534. return this._circleOfConfusion.lensSize;
  70535. },
  70536. /**
  70537. * 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.
  70538. */
  70539. set: function (value) {
  70540. this._circleOfConfusion.lensSize = value;
  70541. },
  70542. enumerable: true,
  70543. configurable: true
  70544. });
  70545. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70546. /**
  70547. * 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.
  70548. */
  70549. set: function (value) {
  70550. this._circleOfConfusion.depthTexture = value;
  70551. },
  70552. enumerable: true,
  70553. configurable: true
  70554. });
  70555. /**
  70556. * Disposes each of the internal effects for a given camera.
  70557. * @param camera The camera to dispose the effect on.
  70558. */
  70559. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70560. for (var effect in this._effects) {
  70561. this._effects[effect].dispose(camera);
  70562. }
  70563. };
  70564. /**
  70565. * Internal
  70566. */
  70567. DepthOfFieldEffect.prototype._updateEffects = function () {
  70568. for (var effect in this._effects) {
  70569. this._effects[effect].updateEffect();
  70570. }
  70571. };
  70572. /**
  70573. * Internal
  70574. * @returns if all the contained post processes are ready.
  70575. */
  70576. DepthOfFieldEffect.prototype._isReady = function () {
  70577. for (var effect in this._effects) {
  70578. if (!this._effects[effect].isReady()) {
  70579. return false;
  70580. }
  70581. }
  70582. return true;
  70583. };
  70584. return DepthOfFieldEffect;
  70585. }(BABYLON.PostProcessRenderEffect));
  70586. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70587. })(BABYLON || (BABYLON = {}));
  70588. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70589. "use strict";
  70590. var BABYLON;
  70591. (function (BABYLON) {
  70592. /**
  70593. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  70594. */
  70595. var BloomMergePostProcess = /** @class */ (function (_super) {
  70596. __extends(BloomMergePostProcess, _super);
  70597. /**
  70598. * Creates a new instance of @see BloomMergePostProcess
  70599. * @param name The name of the effect.
  70600. * @param originalFromInput Post process which's input will be used for the merge.
  70601. * @param blurred Blurred highlights post process which's output will be used.
  70602. * @param weight Weight of the bloom to be added to the original input.
  70603. * @param options The required width/height ratio to downsize to before computing the render pass.
  70604. * @param camera The camera to apply the render pass to.
  70605. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  70606. * @param engine The engine which the post process will be applied. (default: current engine)
  70607. * @param reusable If the post process can be reused on the same frame. (default: false)
  70608. * @param textureType Type of textures used when performing the post process. (default: 0)
  70609. * @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)
  70610. */
  70611. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70612. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70613. if (blockCompilation === void 0) { blockCompilation = false; }
  70614. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  70615. _this.weight = weight;
  70616. _this.onApplyObservable.add(function (effect) {
  70617. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  70618. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  70619. effect.setFloat("bloomWeight", _this.weight);
  70620. });
  70621. if (!blockCompilation) {
  70622. _this.updateEffect();
  70623. }
  70624. return _this;
  70625. }
  70626. return BloomMergePostProcess;
  70627. }(BABYLON.PostProcess));
  70628. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  70629. })(BABYLON || (BABYLON = {}));
  70630. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  70631. "use strict";
  70632. var BABYLON;
  70633. (function (BABYLON) {
  70634. /**
  70635. * 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.
  70636. */
  70637. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  70638. __extends(ExtractHighlightsPostProcess, _super);
  70639. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  70640. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  70641. if (blockCompilation === void 0) { blockCompilation = false; }
  70642. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  70643. /**
  70644. * The luminance threshold, pixels below this value will be set to black.
  70645. */
  70646. _this.threshold = 0.9;
  70647. /**
  70648. * Internal
  70649. */
  70650. _this._exposure = 1;
  70651. /**
  70652. * Post process which has the input texture to be used when performing highlight extraction
  70653. */
  70654. _this._inputPostProcess = null;
  70655. _this.onApplyObservable.add(function (effect) {
  70656. if (_this._inputPostProcess) {
  70657. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  70658. }
  70659. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  70660. effect.setFloat('exposure', _this._exposure);
  70661. });
  70662. return _this;
  70663. }
  70664. return ExtractHighlightsPostProcess;
  70665. }(BABYLON.PostProcess));
  70666. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  70667. })(BABYLON || (BABYLON = {}));
  70668. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  70669. "use strict";
  70670. var BABYLON;
  70671. (function (BABYLON) {
  70672. /**
  70673. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  70674. */
  70675. var BloomEffect = /** @class */ (function (_super) {
  70676. __extends(BloomEffect, _super);
  70677. /**
  70678. * Creates a new instance of @see BloomEffect
  70679. * @param scene The scene the effect belongs to.
  70680. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  70681. * @param bloomKernel The size of the kernel to be used when applying the blur.
  70682. * @param bloomWeight The the strength of bloom.
  70683. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70684. * @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)
  70685. */
  70686. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  70687. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70688. if (blockCompilation === void 0) { blockCompilation = false; }
  70689. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  70690. return _this._effects;
  70691. }, true) || this;
  70692. _this.bloomScale = bloomScale;
  70693. /**
  70694. * Internal
  70695. */
  70696. _this._effects = [];
  70697. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70698. _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);
  70699. _this._blurX.alwaysForcePOT = true;
  70700. _this._blurX.autoClear = false;
  70701. _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);
  70702. _this._blurY.alwaysForcePOT = true;
  70703. _this._blurY.autoClear = false;
  70704. _this.kernel = bloomKernel;
  70705. _this._upscale = new BABYLON.PassPostProcess("upscale", bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70706. _this._upscale.autoClear = false;
  70707. _this._effects = [_this._downscale, _this._blurX, _this._blurY, _this._upscale];
  70708. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70709. _this._merge.autoClear = false;
  70710. _this._effects.push(_this._merge);
  70711. return _this;
  70712. }
  70713. Object.defineProperty(BloomEffect.prototype, "threshold", {
  70714. /**
  70715. * The luminance threshold to find bright areas of the image to bloom.
  70716. */
  70717. get: function () {
  70718. return this._downscale.threshold;
  70719. },
  70720. set: function (value) {
  70721. this._downscale.threshold = value;
  70722. },
  70723. enumerable: true,
  70724. configurable: true
  70725. });
  70726. Object.defineProperty(BloomEffect.prototype, "weight", {
  70727. /**
  70728. * The strength of the bloom.
  70729. */
  70730. get: function () {
  70731. return this._merge.weight;
  70732. },
  70733. set: function (value) {
  70734. this._merge.weight = value;
  70735. },
  70736. enumerable: true,
  70737. configurable: true
  70738. });
  70739. Object.defineProperty(BloomEffect.prototype, "kernel", {
  70740. /**
  70741. * Specifies the size of the bloom blur kernel, relative to the final output size
  70742. */
  70743. get: function () {
  70744. return this._blurX.kernel / this.bloomScale;
  70745. },
  70746. set: function (value) {
  70747. this._blurX.kernel = value * this.bloomScale;
  70748. this._blurY.kernel = value * this.bloomScale;
  70749. },
  70750. enumerable: true,
  70751. configurable: true
  70752. });
  70753. /**
  70754. * Disposes each of the internal effects for a given camera.
  70755. * @param camera The camera to dispose the effect on.
  70756. */
  70757. BloomEffect.prototype.disposeEffects = function (camera) {
  70758. for (var effect in this._effects) {
  70759. this._effects[effect].dispose(camera);
  70760. }
  70761. };
  70762. /**
  70763. * Internal
  70764. */
  70765. BloomEffect.prototype._updateEffects = function () {
  70766. for (var effect in this._effects) {
  70767. this._effects[effect].updateEffect();
  70768. }
  70769. };
  70770. /**
  70771. * Internal
  70772. * @returns if all the contained post processes are ready.
  70773. */
  70774. BloomEffect.prototype._isReady = function () {
  70775. for (var effect in this._effects) {
  70776. if (!this._effects[effect].isReady()) {
  70777. return false;
  70778. }
  70779. }
  70780. return true;
  70781. };
  70782. return BloomEffect;
  70783. }(BABYLON.PostProcessRenderEffect));
  70784. BABYLON.BloomEffect = BloomEffect;
  70785. })(BABYLON || (BABYLON = {}));
  70786. //# sourceMappingURL=babylon.bloomEffect.js.map
  70787. "use strict";
  70788. var BABYLON;
  70789. (function (BABYLON) {
  70790. /**
  70791. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70792. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70793. */
  70794. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70795. __extends(DefaultRenderingPipeline, _super);
  70796. /**
  70797. * @constructor
  70798. * @param {string} name - The rendering pipeline name
  70799. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70800. * @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)
  70801. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70802. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70803. */
  70804. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70805. if (automaticBuild === void 0) { automaticBuild = true; }
  70806. var _this = _super.call(this, scene.getEngine(), name) || this;
  70807. _this._originalCameras = [];
  70808. /**
  70809. * ID of the sharpen post process,
  70810. */
  70811. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70812. /**
  70813. * ID of the image processing post process;
  70814. */
  70815. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70816. /**
  70817. * ID of the Fast Approximate Anti-Aliasing post process;
  70818. */
  70819. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70820. /**
  70821. * ID of the chromatic aberration post process,
  70822. */
  70823. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70824. /**
  70825. * ID of the grain post process
  70826. */
  70827. _this.GrainPostProcessId = "GrainPostProcessEffect";
  70828. /**
  70829. * Animations which can be used to tweak settings over a period of time
  70830. */
  70831. _this.animations = [];
  70832. _this._imageProcessingConfigurationObserver = null;
  70833. // Values
  70834. _this._sharpenEnabled = false;
  70835. _this._bloomEnabled = false;
  70836. _this._depthOfFieldEnabled = false;
  70837. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70838. _this._fxaaEnabled = false;
  70839. _this._imageProcessingEnabled = true;
  70840. _this._bloomScale = 0.5;
  70841. _this._chromaticAberrationEnabled = false;
  70842. _this._grainEnabled = false;
  70843. _this._buildAllowed = true;
  70844. _this._resizeObserver = null;
  70845. _this._hardwareScaleLevel = 1.0;
  70846. _this._bloomKernel = 64;
  70847. /**
  70848. * Specifies the weight of the bloom in the final rendering
  70849. */
  70850. _this._bloomWeight = 0.15;
  70851. /**
  70852. * Specifies the luma threshold for the area that will be blurred by the bloom
  70853. */
  70854. _this._bloomThreshold = 0.9;
  70855. _this._samples = 1;
  70856. _this._hasCleared = false;
  70857. _this._prevPostProcess = null;
  70858. _this._prevPrevPostProcess = null;
  70859. _this._cameras = cameras || [];
  70860. _this._originalCameras = _this._cameras.slice();
  70861. _this._buildAllowed = automaticBuild;
  70862. // Initialize
  70863. _this._scene = scene;
  70864. var caps = _this._scene.getEngine().getCaps();
  70865. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70866. // Misc
  70867. if (_this._hdr) {
  70868. if (caps.textureHalfFloatRender) {
  70869. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70870. }
  70871. else if (caps.textureFloatRender) {
  70872. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70873. }
  70874. }
  70875. else {
  70876. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70877. }
  70878. // Attach
  70879. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70880. var engine = _this._scene.getEngine();
  70881. // Create post processes before hand so they can be modified before enabled.
  70882. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70883. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70884. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70885. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70886. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  70887. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70888. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70889. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70890. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  70891. _this._resizeObserver = engine.onResizeObservable.add(function () {
  70892. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  70893. _this.bloomKernel = _this.bloomKernel;
  70894. });
  70895. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  70896. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  70897. });
  70898. _this._buildPipeline();
  70899. return _this;
  70900. }
  70901. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70902. get: function () {
  70903. return this._sharpenEnabled;
  70904. },
  70905. /**
  70906. * Enable or disable the sharpen process from the pipeline
  70907. */
  70908. set: function (enabled) {
  70909. if (this._sharpenEnabled === enabled) {
  70910. return;
  70911. }
  70912. this._sharpenEnabled = enabled;
  70913. this._buildPipeline();
  70914. },
  70915. enumerable: true,
  70916. configurable: true
  70917. });
  70918. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  70919. /**
  70920. * Specifies the size of the bloom blur kernel, relative to the final output size
  70921. */
  70922. get: function () {
  70923. return this._bloomKernel;
  70924. },
  70925. set: function (value) {
  70926. this._bloomKernel = value;
  70927. this.bloom.kernel = value / this._hardwareScaleLevel;
  70928. },
  70929. enumerable: true,
  70930. configurable: true
  70931. });
  70932. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70933. get: function () {
  70934. return this._bloomWeight;
  70935. },
  70936. /**
  70937. * The strength of the bloom.
  70938. */
  70939. set: function (value) {
  70940. if (this._bloomWeight === value) {
  70941. return;
  70942. }
  70943. this.bloom.weight = value;
  70944. this._bloomWeight = value;
  70945. },
  70946. enumerable: true,
  70947. configurable: true
  70948. });
  70949. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  70950. get: function () {
  70951. return this._bloomThreshold;
  70952. },
  70953. /**
  70954. * The strength of the bloom.
  70955. */
  70956. set: function (value) {
  70957. if (this._bloomThreshold === value) {
  70958. return;
  70959. }
  70960. this.bloom.threshold = value;
  70961. this._bloomThreshold = value;
  70962. },
  70963. enumerable: true,
  70964. configurable: true
  70965. });
  70966. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70967. get: function () {
  70968. return this._bloomScale;
  70969. },
  70970. /**
  70971. * The scale of the bloom, lower value will provide better performance.
  70972. */
  70973. set: function (value) {
  70974. if (this._bloomScale === value) {
  70975. return;
  70976. }
  70977. this._bloomScale = value;
  70978. // recreate bloom and dispose old as this setting is not dynamic
  70979. this._rebuildBloom();
  70980. this._buildPipeline();
  70981. },
  70982. enumerable: true,
  70983. configurable: true
  70984. });
  70985. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70986. get: function () {
  70987. return this._bloomEnabled;
  70988. },
  70989. /**
  70990. * Enable or disable the bloom from the pipeline
  70991. */
  70992. set: function (enabled) {
  70993. if (this._bloomEnabled === enabled) {
  70994. return;
  70995. }
  70996. this._bloomEnabled = enabled;
  70997. this._buildPipeline();
  70998. },
  70999. enumerable: true,
  71000. configurable: true
  71001. });
  71002. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  71003. // recreate bloom and dispose old as this setting is not dynamic
  71004. var oldBloom = this.bloom;
  71005. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  71006. this.bloom.threshold = oldBloom.threshold;
  71007. for (var i = 0; i < this._cameras.length; i++) {
  71008. oldBloom.disposeEffects(this._cameras[i]);
  71009. }
  71010. };
  71011. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  71012. /**
  71013. * If the depth of field is enabled.
  71014. */
  71015. get: function () {
  71016. return this._depthOfFieldEnabled;
  71017. },
  71018. set: function (enabled) {
  71019. if (this._depthOfFieldEnabled === enabled) {
  71020. return;
  71021. }
  71022. this._depthOfFieldEnabled = enabled;
  71023. this._buildPipeline();
  71024. },
  71025. enumerable: true,
  71026. configurable: true
  71027. });
  71028. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  71029. /**
  71030. * Blur level of the depth of field effect. (Higher blur will effect performance)
  71031. */
  71032. get: function () {
  71033. return this._depthOfFieldBlurLevel;
  71034. },
  71035. set: function (value) {
  71036. if (this._depthOfFieldBlurLevel === value) {
  71037. return;
  71038. }
  71039. this._depthOfFieldBlurLevel = value;
  71040. // recreate dof and dispose old as this setting is not dynamic
  71041. var oldDof = this.depthOfField;
  71042. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  71043. this.depthOfField.focalLength = oldDof.focalLength;
  71044. this.depthOfField.focusDistance = oldDof.focusDistance;
  71045. this.depthOfField.fStop = oldDof.fStop;
  71046. this.depthOfField.lensSize = oldDof.lensSize;
  71047. for (var i = 0; i < this._cameras.length; i++) {
  71048. oldDof.disposeEffects(this._cameras[i]);
  71049. }
  71050. this._buildPipeline();
  71051. },
  71052. enumerable: true,
  71053. configurable: true
  71054. });
  71055. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  71056. get: function () {
  71057. return this._fxaaEnabled;
  71058. },
  71059. /**
  71060. * If the anti aliasing is enabled.
  71061. */
  71062. set: function (enabled) {
  71063. if (this._fxaaEnabled === enabled) {
  71064. return;
  71065. }
  71066. this._fxaaEnabled = enabled;
  71067. this._buildPipeline();
  71068. },
  71069. enumerable: true,
  71070. configurable: true
  71071. });
  71072. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  71073. get: function () {
  71074. return this._samples;
  71075. },
  71076. /**
  71077. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  71078. */
  71079. set: function (sampleCount) {
  71080. if (this._samples === sampleCount) {
  71081. return;
  71082. }
  71083. this._samples = sampleCount;
  71084. this._buildPipeline();
  71085. },
  71086. enumerable: true,
  71087. configurable: true
  71088. });
  71089. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  71090. get: function () {
  71091. return this._imageProcessingEnabled;
  71092. },
  71093. /**
  71094. * If image processing is enabled.
  71095. */
  71096. set: function (enabled) {
  71097. if (this._imageProcessingEnabled === enabled) {
  71098. return;
  71099. }
  71100. this._imageProcessingEnabled = enabled;
  71101. this._buildPipeline();
  71102. },
  71103. enumerable: true,
  71104. configurable: true
  71105. });
  71106. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  71107. get: function () {
  71108. return this._chromaticAberrationEnabled;
  71109. },
  71110. /**
  71111. * Enable or disable the chromaticAberration process from the pipeline
  71112. */
  71113. set: function (enabled) {
  71114. if (this._chromaticAberrationEnabled === enabled) {
  71115. return;
  71116. }
  71117. this._chromaticAberrationEnabled = enabled;
  71118. this._buildPipeline();
  71119. },
  71120. enumerable: true,
  71121. configurable: true
  71122. });
  71123. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  71124. get: function () {
  71125. return this._grainEnabled;
  71126. },
  71127. /**
  71128. * Enable or disable the grain process from the pipeline
  71129. */
  71130. set: function (enabled) {
  71131. if (this._grainEnabled === enabled) {
  71132. return;
  71133. }
  71134. this._grainEnabled = enabled;
  71135. this._buildPipeline();
  71136. },
  71137. enumerable: true,
  71138. configurable: true
  71139. });
  71140. /**
  71141. * Force the compilation of the entire pipeline.
  71142. */
  71143. DefaultRenderingPipeline.prototype.prepare = function () {
  71144. var previousState = this._buildAllowed;
  71145. this._buildAllowed = true;
  71146. this._buildPipeline();
  71147. this._buildAllowed = previousState;
  71148. };
  71149. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  71150. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  71151. if (this._hasCleared) {
  71152. postProcess.autoClear = false;
  71153. }
  71154. else {
  71155. postProcess.autoClear = true;
  71156. this._scene.autoClear = false;
  71157. this._hasCleared = true;
  71158. }
  71159. if (!skipTextureSharing) {
  71160. if (this._prevPrevPostProcess) {
  71161. postProcess.shareOutputWith(this._prevPrevPostProcess);
  71162. }
  71163. else {
  71164. postProcess.useOwnOutput();
  71165. }
  71166. if (this._prevPostProcess) {
  71167. this._prevPrevPostProcess = this._prevPostProcess;
  71168. }
  71169. this._prevPostProcess = postProcess;
  71170. }
  71171. };
  71172. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  71173. var _this = this;
  71174. if (!this._buildAllowed) {
  71175. return;
  71176. }
  71177. this._scene.autoClear = true;
  71178. var engine = this._scene.getEngine();
  71179. this._disposePostProcesses();
  71180. if (this._cameras !== null) {
  71181. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71182. // get back cameras to be used to reattach pipeline
  71183. this._cameras = this._originalCameras.slice();
  71184. }
  71185. this._reset();
  71186. this._prevPostProcess = null;
  71187. this._prevPrevPostProcess = null;
  71188. this._hasCleared = false;
  71189. if (this.depthOfFieldEnabled) {
  71190. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  71191. this.depthOfField.depthTexture = depthTexture;
  71192. if (!this.depthOfField._isReady()) {
  71193. this.depthOfField._updateEffects();
  71194. }
  71195. this.addEffect(this.depthOfField);
  71196. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  71197. }
  71198. if (this.bloomEnabled) {
  71199. if (!this.bloom._isReady()) {
  71200. this.bloom._updateEffects();
  71201. }
  71202. this.addEffect(this.bloom);
  71203. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  71204. }
  71205. if (this._imageProcessingEnabled) {
  71206. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71207. if (this._hdr) {
  71208. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  71209. this._setAutoClearAndTextureSharing(this.imageProcessing);
  71210. }
  71211. else {
  71212. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  71213. }
  71214. }
  71215. if (this.sharpenEnabled) {
  71216. if (!this.sharpen.isReady()) {
  71217. this.sharpen.updateEffect();
  71218. }
  71219. this.addEffect(this._sharpenEffect);
  71220. this._setAutoClearAndTextureSharing(this.sharpen);
  71221. }
  71222. if (this.grainEnabled) {
  71223. if (!this.grain.isReady()) {
  71224. this.grain.updateEffect();
  71225. }
  71226. this.addEffect(this._grainEffect);
  71227. this._setAutoClearAndTextureSharing(this.grain);
  71228. }
  71229. if (this.chromaticAberrationEnabled) {
  71230. if (!this.chromaticAberration.isReady()) {
  71231. this.chromaticAberration.updateEffect();
  71232. }
  71233. this.addEffect(this._chromaticAberrationEffect);
  71234. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  71235. }
  71236. if (this.fxaaEnabled) {
  71237. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  71238. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  71239. this._setAutoClearAndTextureSharing(this.fxaa, true);
  71240. }
  71241. if (this._cameras !== null) {
  71242. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  71243. }
  71244. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  71245. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  71246. }
  71247. };
  71248. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  71249. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  71250. for (var i = 0; i < this._cameras.length; i++) {
  71251. var camera = this._cameras[i];
  71252. if (this.imageProcessing) {
  71253. this.imageProcessing.dispose(camera);
  71254. }
  71255. if (this.fxaa) {
  71256. this.fxaa.dispose(camera);
  71257. }
  71258. // These are created in the constructor and should not be disposed on every pipeline change
  71259. if (disposeNonRecreated) {
  71260. if (this.sharpen) {
  71261. this.sharpen.dispose(camera);
  71262. }
  71263. if (this.depthOfField) {
  71264. this.depthOfField.disposeEffects(camera);
  71265. }
  71266. if (this.bloom) {
  71267. this.bloom.disposeEffects(camera);
  71268. }
  71269. if (this.chromaticAberration) {
  71270. this.chromaticAberration.dispose(camera);
  71271. }
  71272. if (this.grain) {
  71273. this.grain.dispose(camera);
  71274. }
  71275. }
  71276. }
  71277. this.imageProcessing = null;
  71278. this.fxaa = null;
  71279. if (disposeNonRecreated) {
  71280. this.sharpen = null;
  71281. this._sharpenEffect = null;
  71282. this.depthOfField = null;
  71283. this.bloom = null;
  71284. this.chromaticAberration = null;
  71285. this._chromaticAberrationEffect = null;
  71286. this.grain = null;
  71287. this._grainEffect = null;
  71288. }
  71289. };
  71290. /**
  71291. * Dispose of the pipeline and stop all post processes
  71292. */
  71293. DefaultRenderingPipeline.prototype.dispose = function () {
  71294. this._disposePostProcesses(true);
  71295. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  71296. this._scene.autoClear = true;
  71297. if (this._resizeObserver) {
  71298. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  71299. this._resizeObserver = null;
  71300. }
  71301. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  71302. _super.prototype.dispose.call(this);
  71303. };
  71304. /**
  71305. * Serialize the rendering pipeline (Used when exporting)
  71306. * @returns the serialized object
  71307. */
  71308. DefaultRenderingPipeline.prototype.serialize = function () {
  71309. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  71310. serializationObject.customType = "DefaultRenderingPipeline";
  71311. return serializationObject;
  71312. };
  71313. /**
  71314. * Parse the serialized pipeline
  71315. * @param source Source pipeline.
  71316. * @param scene The scene to load the pipeline to.
  71317. * @param rootUrl The URL of the serialized pipeline.
  71318. * @returns An instantiated pipeline from the serialized object.
  71319. */
  71320. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  71321. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  71322. };
  71323. __decorate([
  71324. BABYLON.serialize()
  71325. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  71326. __decorate([
  71327. BABYLON.serialize()
  71328. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  71329. __decorate([
  71330. BABYLON.serialize()
  71331. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  71332. __decorate([
  71333. BABYLON.serialize()
  71334. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  71335. __decorate([
  71336. BABYLON.serialize()
  71337. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  71338. __decorate([
  71339. BABYLON.serialize()
  71340. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  71341. __decorate([
  71342. BABYLON.serialize()
  71343. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  71344. __decorate([
  71345. BABYLON.serialize()
  71346. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  71347. __decorate([
  71348. BABYLON.serialize()
  71349. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  71350. __decorate([
  71351. BABYLON.serialize()
  71352. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  71353. __decorate([
  71354. BABYLON.serialize()
  71355. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  71356. __decorate([
  71357. BABYLON.serialize()
  71358. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  71359. __decorate([
  71360. BABYLON.serialize()
  71361. ], DefaultRenderingPipeline.prototype, "samples", null);
  71362. __decorate([
  71363. BABYLON.serialize()
  71364. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  71365. __decorate([
  71366. BABYLON.serialize()
  71367. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  71368. __decorate([
  71369. BABYLON.serialize()
  71370. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  71371. return DefaultRenderingPipeline;
  71372. }(BABYLON.PostProcessRenderPipeline));
  71373. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  71374. })(BABYLON || (BABYLON = {}));
  71375. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  71376. "use strict";
  71377. var BABYLON;
  71378. (function (BABYLON) {
  71379. /**
  71380. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  71381. */
  71382. var GeometryBufferRenderer = /** @class */ (function () {
  71383. /**
  71384. * Creates a new G Buffer for the scene
  71385. * @param scene The scene the buffer belongs to
  71386. * @param ratio How big is the buffer related to the main canvas.
  71387. */
  71388. function GeometryBufferRenderer(scene, ratio) {
  71389. if (ratio === void 0) { ratio = 1; }
  71390. this._enablePosition = false;
  71391. this._scene = scene;
  71392. this._ratio = ratio;
  71393. // Render target
  71394. this._createRenderTargets();
  71395. }
  71396. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  71397. /**
  71398. * Set the render list (meshes to be rendered) used in the G buffer.
  71399. */
  71400. set: function (meshes) {
  71401. this._multiRenderTarget.renderList = meshes;
  71402. },
  71403. enumerable: true,
  71404. configurable: true
  71405. });
  71406. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  71407. /**
  71408. * Gets wether or not G buffer are supported by the running hardware.
  71409. * This requires draw buffer supports
  71410. */
  71411. get: function () {
  71412. return this._multiRenderTarget.isSupported;
  71413. },
  71414. enumerable: true,
  71415. configurable: true
  71416. });
  71417. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  71418. /**
  71419. * Gets wether or not position are enabled for the G buffer.
  71420. */
  71421. get: function () {
  71422. return this._enablePosition;
  71423. },
  71424. /**
  71425. * Sets wether or not position are enabled for the G buffer.
  71426. */
  71427. set: function (enable) {
  71428. this._enablePosition = enable;
  71429. this.dispose();
  71430. this._createRenderTargets();
  71431. },
  71432. enumerable: true,
  71433. configurable: true
  71434. });
  71435. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  71436. /**
  71437. * Gets the scene associated with the buffer.
  71438. */
  71439. get: function () {
  71440. return this._scene;
  71441. },
  71442. enumerable: true,
  71443. configurable: true
  71444. });
  71445. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  71446. /**
  71447. * Gets the ratio used by the buffer during its creation.
  71448. * How big is the buffer related to the main canvas.
  71449. */
  71450. get: function () {
  71451. return this._ratio;
  71452. },
  71453. enumerable: true,
  71454. configurable: true
  71455. });
  71456. /**
  71457. * Checks wether everything is ready to render a submesh to the G buffer.
  71458. * @param subMesh the submesh to check readiness for
  71459. * @param useInstances is the mesh drawn using instance or not
  71460. * @returns true if ready otherwise false
  71461. */
  71462. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  71463. var material = subMesh.getMaterial();
  71464. if (material && material.disableDepthWrite) {
  71465. return false;
  71466. }
  71467. var defines = [];
  71468. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71469. var mesh = subMesh.getMesh();
  71470. // Alpha test
  71471. if (material && material.needAlphaTesting()) {
  71472. defines.push("#define ALPHATEST");
  71473. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71474. attribs.push(BABYLON.VertexBuffer.UVKind);
  71475. defines.push("#define UV1");
  71476. }
  71477. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71478. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71479. defines.push("#define UV2");
  71480. }
  71481. }
  71482. // Buffers
  71483. if (this._enablePosition) {
  71484. defines.push("#define POSITION");
  71485. }
  71486. // Bones
  71487. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71488. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71489. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71490. if (mesh.numBoneInfluencers > 4) {
  71491. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71492. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71493. }
  71494. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71495. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71496. }
  71497. else {
  71498. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71499. }
  71500. // Instances
  71501. if (useInstances) {
  71502. defines.push("#define INSTANCES");
  71503. attribs.push("world0");
  71504. attribs.push("world1");
  71505. attribs.push("world2");
  71506. attribs.push("world3");
  71507. }
  71508. // Get correct effect
  71509. var join = defines.join("\n");
  71510. if (this._cachedDefines !== join) {
  71511. this._cachedDefines = join;
  71512. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  71513. }
  71514. return this._effect.isReady();
  71515. };
  71516. /**
  71517. * Gets the current underlying G Buffer.
  71518. * @returns the buffer
  71519. */
  71520. GeometryBufferRenderer.prototype.getGBuffer = function () {
  71521. return this._multiRenderTarget;
  71522. };
  71523. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  71524. /**
  71525. * Gets the number of samples used to render the buffer (anti aliasing).
  71526. */
  71527. get: function () {
  71528. return this._multiRenderTarget.samples;
  71529. },
  71530. /**
  71531. * Sets the number of samples used to render the buffer (anti aliasing).
  71532. */
  71533. set: function (value) {
  71534. this._multiRenderTarget.samples = value;
  71535. },
  71536. enumerable: true,
  71537. configurable: true
  71538. });
  71539. /**
  71540. * Disposes the renderer and frees up associated resources.
  71541. */
  71542. GeometryBufferRenderer.prototype.dispose = function () {
  71543. this.getGBuffer().dispose();
  71544. };
  71545. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  71546. var _this = this;
  71547. var engine = this._scene.getEngine();
  71548. var count = this._enablePosition ? 3 : 2;
  71549. 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 });
  71550. if (!this.isSupported) {
  71551. return;
  71552. }
  71553. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71554. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71555. this._multiRenderTarget.refreshRate = 1;
  71556. this._multiRenderTarget.renderParticles = false;
  71557. this._multiRenderTarget.renderList = null;
  71558. // set default depth value to 1.0 (far away)
  71559. this._multiRenderTarget.onClearObservable.add(function (engine) {
  71560. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  71561. });
  71562. // Custom render function
  71563. var renderSubMesh = function (subMesh) {
  71564. var mesh = subMesh.getRenderingMesh();
  71565. var scene = _this._scene;
  71566. var engine = scene.getEngine();
  71567. var material = subMesh.getMaterial();
  71568. if (!material) {
  71569. return;
  71570. }
  71571. // Culling
  71572. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  71573. // Managing instances
  71574. var batch = mesh._getInstancesRenderList(subMesh._id);
  71575. if (batch.mustReturn) {
  71576. return;
  71577. }
  71578. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71579. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  71580. engine.enableEffect(_this._effect);
  71581. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71582. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71583. _this._effect.setMatrix("view", scene.getViewMatrix());
  71584. // Alpha test
  71585. if (material && material.needAlphaTesting()) {
  71586. var alphaTexture = material.getAlphaTestTexture();
  71587. if (alphaTexture) {
  71588. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71589. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71590. }
  71591. }
  71592. // Bones
  71593. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71594. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71595. }
  71596. // Draw
  71597. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71598. }
  71599. };
  71600. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71601. var index;
  71602. if (depthOnlySubMeshes.length) {
  71603. engine.setColorWrite(false);
  71604. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71605. renderSubMesh(depthOnlySubMeshes.data[index]);
  71606. }
  71607. engine.setColorWrite(true);
  71608. }
  71609. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71610. renderSubMesh(opaqueSubMeshes.data[index]);
  71611. }
  71612. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71613. renderSubMesh(alphaTestSubMeshes.data[index]);
  71614. }
  71615. };
  71616. };
  71617. return GeometryBufferRenderer;
  71618. }());
  71619. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71620. })(BABYLON || (BABYLON = {}));
  71621. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71622. "use strict";
  71623. var BABYLON;
  71624. (function (BABYLON) {
  71625. var RefractionPostProcess = /** @class */ (function (_super) {
  71626. __extends(RefractionPostProcess, _super);
  71627. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71628. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71629. _this.color = color;
  71630. _this.depth = depth;
  71631. _this.colorLevel = colorLevel;
  71632. _this._ownRefractionTexture = true;
  71633. _this.onActivateObservable.add(function (cam) {
  71634. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71635. });
  71636. _this.onApplyObservable.add(function (effect) {
  71637. effect.setColor3("baseColor", _this.color);
  71638. effect.setFloat("depth", _this.depth);
  71639. effect.setFloat("colorLevel", _this.colorLevel);
  71640. effect.setTexture("refractionSampler", _this._refTexture);
  71641. });
  71642. return _this;
  71643. }
  71644. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71645. /**
  71646. * Gets or sets the refraction texture
  71647. * Please note that you are responsible for disposing the texture if you set it manually
  71648. */
  71649. get: function () {
  71650. return this._refTexture;
  71651. },
  71652. set: function (value) {
  71653. if (this._refTexture && this._ownRefractionTexture) {
  71654. this._refTexture.dispose();
  71655. }
  71656. this._refTexture = value;
  71657. this._ownRefractionTexture = false;
  71658. },
  71659. enumerable: true,
  71660. configurable: true
  71661. });
  71662. // Methods
  71663. RefractionPostProcess.prototype.dispose = function (camera) {
  71664. if (this._refTexture && this._ownRefractionTexture) {
  71665. this._refTexture.dispose();
  71666. this._refTexture = null;
  71667. }
  71668. _super.prototype.dispose.call(this, camera);
  71669. };
  71670. return RefractionPostProcess;
  71671. }(BABYLON.PostProcess));
  71672. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71673. })(BABYLON || (BABYLON = {}));
  71674. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71675. "use strict";
  71676. var BABYLON;
  71677. (function (BABYLON) {
  71678. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71679. __extends(BlackAndWhitePostProcess, _super);
  71680. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71681. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71682. _this.degree = 1;
  71683. _this.onApplyObservable.add(function (effect) {
  71684. effect.setFloat("degree", _this.degree);
  71685. });
  71686. return _this;
  71687. }
  71688. return BlackAndWhitePostProcess;
  71689. }(BABYLON.PostProcess));
  71690. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71691. })(BABYLON || (BABYLON = {}));
  71692. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71693. "use strict";
  71694. var BABYLON;
  71695. (function (BABYLON) {
  71696. /**
  71697. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71698. * input texture to perform effects such as edge detection or sharpening
  71699. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71700. */
  71701. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71702. __extends(ConvolutionPostProcess, _super);
  71703. /**
  71704. * Creates a new instance ConvolutionPostProcess
  71705. * @param name The name of the effect.
  71706. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71707. * @param options The required width/height ratio to downsize to before computing the render pass.
  71708. * @param camera The camera to apply the render pass to.
  71709. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71710. * @param engine The engine which the post process will be applied. (default: current engine)
  71711. * @param reusable If the post process can be reused on the same frame. (default: false)
  71712. * @param textureType Type of textures used when performing the post process. (default: 0)
  71713. */
  71714. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71715. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71716. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71717. _this.kernel = kernel;
  71718. _this.onApply = function (effect) {
  71719. effect.setFloat2("screenSize", _this.width, _this.height);
  71720. effect.setArray("kernel", _this.kernel);
  71721. };
  71722. return _this;
  71723. }
  71724. // Statics
  71725. /**
  71726. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71727. */
  71728. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71729. /**
  71730. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71731. */
  71732. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71733. /**
  71734. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71735. */
  71736. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71737. /**
  71738. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71739. */
  71740. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71741. /**
  71742. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71743. */
  71744. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71745. /**
  71746. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71747. */
  71748. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71749. return ConvolutionPostProcess;
  71750. }(BABYLON.PostProcess));
  71751. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71752. })(BABYLON || (BABYLON = {}));
  71753. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71754. "use strict";
  71755. var BABYLON;
  71756. (function (BABYLON) {
  71757. var FilterPostProcess = /** @class */ (function (_super) {
  71758. __extends(FilterPostProcess, _super);
  71759. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71760. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71761. _this.kernelMatrix = kernelMatrix;
  71762. _this.onApply = function (effect) {
  71763. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71764. };
  71765. return _this;
  71766. }
  71767. return FilterPostProcess;
  71768. }(BABYLON.PostProcess));
  71769. BABYLON.FilterPostProcess = FilterPostProcess;
  71770. })(BABYLON || (BABYLON = {}));
  71771. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71772. "use strict";
  71773. var BABYLON;
  71774. (function (BABYLON) {
  71775. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71776. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71777. __extends(VolumetricLightScatteringPostProcess, _super);
  71778. /**
  71779. * @constructor
  71780. * @param {string} name - The post-process name
  71781. * @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)
  71782. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71783. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71784. * @param {number} samples - The post-process quality, default 100
  71785. * @param {number} samplingMode - The post-process filtering mode
  71786. * @param {BABYLON.Engine} engine - The babylon engine
  71787. * @param {boolean} reusable - If the post-process is reusable
  71788. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71789. */
  71790. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71791. if (samples === void 0) { samples = 100; }
  71792. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71793. 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;
  71794. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71795. /**
  71796. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71797. * @type {Vector3}
  71798. */
  71799. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71800. /**
  71801. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71802. * @type {boolean}
  71803. */
  71804. _this.useCustomMeshPosition = false;
  71805. /**
  71806. * If the post-process should inverse the light scattering direction
  71807. * @type {boolean}
  71808. */
  71809. _this.invert = true;
  71810. /**
  71811. * Array containing the excluded meshes not rendered in the internal pass
  71812. */
  71813. _this.excludedMeshes = new Array();
  71814. /**
  71815. * Controls the overall intensity of the post-process
  71816. * @type {number}
  71817. */
  71818. _this.exposure = 0.3;
  71819. /**
  71820. * Dissipates each sample's contribution in range [0, 1]
  71821. * @type {number}
  71822. */
  71823. _this.decay = 0.96815;
  71824. /**
  71825. * Controls the overall intensity of each sample
  71826. * @type {number}
  71827. */
  71828. _this.weight = 0.58767;
  71829. /**
  71830. * Controls the density of each sample
  71831. * @type {number}
  71832. */
  71833. _this.density = 0.926;
  71834. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71835. engine = scene.getEngine();
  71836. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71837. // Configure mesh
  71838. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71839. // Configure
  71840. _this._createPass(scene, ratio.passRatio || ratio);
  71841. _this.onActivate = function (camera) {
  71842. if (!_this.isSupported) {
  71843. _this.dispose(camera);
  71844. }
  71845. _this.onActivate = null;
  71846. };
  71847. _this.onApplyObservable.add(function (effect) {
  71848. _this._updateMeshScreenCoordinates(scene);
  71849. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71850. effect.setFloat("exposure", _this.exposure);
  71851. effect.setFloat("decay", _this.decay);
  71852. effect.setFloat("weight", _this.weight);
  71853. effect.setFloat("density", _this.density);
  71854. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71855. });
  71856. return _this;
  71857. }
  71858. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71859. get: function () {
  71860. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71861. return false;
  71862. },
  71863. set: function (useDiffuseColor) {
  71864. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71865. },
  71866. enumerable: true,
  71867. configurable: true
  71868. });
  71869. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71870. return "VolumetricLightScatteringPostProcess";
  71871. };
  71872. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71873. var mesh = subMesh.getMesh();
  71874. // Render this.mesh as default
  71875. if (mesh === this.mesh && mesh.material) {
  71876. return mesh.material.isReady(mesh);
  71877. }
  71878. var defines = [];
  71879. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71880. var material = subMesh.getMaterial();
  71881. // Alpha test
  71882. if (material) {
  71883. if (material.needAlphaTesting()) {
  71884. defines.push("#define ALPHATEST");
  71885. }
  71886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71887. attribs.push(BABYLON.VertexBuffer.UVKind);
  71888. defines.push("#define UV1");
  71889. }
  71890. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71891. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71892. defines.push("#define UV2");
  71893. }
  71894. }
  71895. // Bones
  71896. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71897. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71898. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71899. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71900. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71901. }
  71902. else {
  71903. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71904. }
  71905. // Instances
  71906. if (useInstances) {
  71907. defines.push("#define INSTANCES");
  71908. attribs.push("world0");
  71909. attribs.push("world1");
  71910. attribs.push("world2");
  71911. attribs.push("world3");
  71912. }
  71913. // Get correct effect
  71914. var join = defines.join("\n");
  71915. if (this._cachedDefines !== join) {
  71916. this._cachedDefines = join;
  71917. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71918. }
  71919. return this._volumetricLightScatteringPass.isReady();
  71920. };
  71921. /**
  71922. * Sets the new light position for light scattering effect
  71923. * @param {BABYLON.Vector3} The new custom light position
  71924. */
  71925. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71926. this.customMeshPosition = position;
  71927. };
  71928. /**
  71929. * Returns the light position for light scattering effect
  71930. * @return {BABYLON.Vector3} The custom light position
  71931. */
  71932. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71933. return this.customMeshPosition;
  71934. };
  71935. /**
  71936. * Disposes the internal assets and detaches the post-process from the camera
  71937. */
  71938. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71939. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71940. if (rttIndex !== -1) {
  71941. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71942. }
  71943. this._volumetricLightScatteringRTT.dispose();
  71944. _super.prototype.dispose.call(this, camera);
  71945. };
  71946. /**
  71947. * Returns the render target texture used by the post-process
  71948. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71949. */
  71950. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71951. return this._volumetricLightScatteringRTT;
  71952. };
  71953. // Private methods
  71954. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71955. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71956. return true;
  71957. }
  71958. return false;
  71959. };
  71960. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71961. var _this = this;
  71962. var engine = scene.getEngine();
  71963. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71964. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71965. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71966. this._volumetricLightScatteringRTT.renderList = null;
  71967. this._volumetricLightScatteringRTT.renderParticles = false;
  71968. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71969. var camera = this.getCamera();
  71970. if (camera) {
  71971. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71972. }
  71973. else {
  71974. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71975. }
  71976. // Custom render function for submeshes
  71977. var renderSubMesh = function (subMesh) {
  71978. var mesh = subMesh.getRenderingMesh();
  71979. if (_this._meshExcluded(mesh)) {
  71980. return;
  71981. }
  71982. var material = subMesh.getMaterial();
  71983. if (!material) {
  71984. return;
  71985. }
  71986. var scene = mesh.getScene();
  71987. var engine = scene.getEngine();
  71988. // Culling
  71989. engine.setState(material.backFaceCulling);
  71990. // Managing instances
  71991. var batch = mesh._getInstancesRenderList(subMesh._id);
  71992. if (batch.mustReturn) {
  71993. return;
  71994. }
  71995. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71996. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71997. var effect = _this._volumetricLightScatteringPass;
  71998. if (mesh === _this.mesh) {
  71999. if (subMesh.effect) {
  72000. effect = subMesh.effect;
  72001. }
  72002. else {
  72003. effect = material.getEffect();
  72004. }
  72005. }
  72006. engine.enableEffect(effect);
  72007. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  72008. if (mesh === _this.mesh) {
  72009. material.bind(mesh.getWorldMatrix(), mesh);
  72010. }
  72011. else {
  72012. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  72013. // Alpha test
  72014. if (material && material.needAlphaTesting()) {
  72015. var alphaTexture = material.getAlphaTestTexture();
  72016. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  72017. if (alphaTexture) {
  72018. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72019. }
  72020. }
  72021. // Bones
  72022. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72023. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72024. }
  72025. }
  72026. // Draw
  72027. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  72028. }
  72029. };
  72030. // Render target texture callbacks
  72031. var savedSceneClearColor;
  72032. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  72033. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  72034. savedSceneClearColor = scene.clearColor;
  72035. scene.clearColor = sceneClearColor;
  72036. });
  72037. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  72038. scene.clearColor = savedSceneClearColor;
  72039. });
  72040. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72041. var engine = scene.getEngine();
  72042. var index;
  72043. if (depthOnlySubMeshes.length) {
  72044. engine.setColorWrite(false);
  72045. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72046. renderSubMesh(depthOnlySubMeshes.data[index]);
  72047. }
  72048. engine.setColorWrite(true);
  72049. }
  72050. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72051. renderSubMesh(opaqueSubMeshes.data[index]);
  72052. }
  72053. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72054. renderSubMesh(alphaTestSubMeshes.data[index]);
  72055. }
  72056. if (transparentSubMeshes.length) {
  72057. // Sort sub meshes
  72058. for (index = 0; index < transparentSubMeshes.length; index++) {
  72059. var submesh = transparentSubMeshes.data[index];
  72060. var boundingInfo = submesh.getBoundingInfo();
  72061. if (boundingInfo && scene.activeCamera) {
  72062. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  72063. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  72064. }
  72065. }
  72066. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  72067. sortedArray.sort(function (a, b) {
  72068. // Alpha index first
  72069. if (a._alphaIndex > b._alphaIndex) {
  72070. return 1;
  72071. }
  72072. if (a._alphaIndex < b._alphaIndex) {
  72073. return -1;
  72074. }
  72075. // Then distance to camera
  72076. if (a._distanceToCamera < b._distanceToCamera) {
  72077. return 1;
  72078. }
  72079. if (a._distanceToCamera > b._distanceToCamera) {
  72080. return -1;
  72081. }
  72082. return 0;
  72083. });
  72084. // Render sub meshes
  72085. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  72086. for (index = 0; index < sortedArray.length; index++) {
  72087. renderSubMesh(sortedArray[index]);
  72088. }
  72089. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  72090. }
  72091. };
  72092. };
  72093. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  72094. var transform = scene.getTransformMatrix();
  72095. var meshPosition;
  72096. if (this.useCustomMeshPosition) {
  72097. meshPosition = this.customMeshPosition;
  72098. }
  72099. else if (this.attachedNode) {
  72100. meshPosition = this.attachedNode.position;
  72101. }
  72102. else {
  72103. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  72104. }
  72105. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  72106. this._screenCoordinates.x = pos.x / this._viewPort.width;
  72107. this._screenCoordinates.y = pos.y / this._viewPort.height;
  72108. if (this.invert)
  72109. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  72110. };
  72111. // Static methods
  72112. /**
  72113. * Creates a default mesh for the Volumeric Light Scattering post-process
  72114. * @param {string} The mesh name
  72115. * @param {BABYLON.Scene} The scene where to create the mesh
  72116. * @return {BABYLON.Mesh} the default mesh
  72117. */
  72118. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  72119. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  72120. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  72121. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  72122. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  72123. mesh.material = material;
  72124. return mesh;
  72125. };
  72126. __decorate([
  72127. BABYLON.serializeAsVector3()
  72128. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  72129. __decorate([
  72130. BABYLON.serialize()
  72131. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  72132. __decorate([
  72133. BABYLON.serialize()
  72134. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  72135. __decorate([
  72136. BABYLON.serializeAsMeshReference()
  72137. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  72138. __decorate([
  72139. BABYLON.serialize()
  72140. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  72141. __decorate([
  72142. BABYLON.serialize()
  72143. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  72144. __decorate([
  72145. BABYLON.serialize()
  72146. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  72147. __decorate([
  72148. BABYLON.serialize()
  72149. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  72150. __decorate([
  72151. BABYLON.serialize()
  72152. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  72153. return VolumetricLightScatteringPostProcess;
  72154. }(BABYLON.PostProcess));
  72155. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  72156. })(BABYLON || (BABYLON = {}));
  72157. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  72158. "use strict";
  72159. //
  72160. // This post-process allows the modification of rendered colors by using
  72161. // a 'look-up table' (LUT). This effect is also called Color Grading.
  72162. //
  72163. // The object needs to be provided an url to a texture containing the color
  72164. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  72165. // Use an image editing software to tweak the LUT to match your needs.
  72166. //
  72167. // For an example of a color LUT, see here:
  72168. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  72169. // For explanations on color grading, see here:
  72170. // http://udn.epicgames.com/Three/ColorGrading.html
  72171. //
  72172. var BABYLON;
  72173. (function (BABYLON) {
  72174. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  72175. __extends(ColorCorrectionPostProcess, _super);
  72176. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  72177. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  72178. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72179. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  72180. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72181. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72182. _this.onApply = function (effect) {
  72183. effect.setTexture("colorTable", _this._colorTableTexture);
  72184. };
  72185. return _this;
  72186. }
  72187. return ColorCorrectionPostProcess;
  72188. }(BABYLON.PostProcess));
  72189. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  72190. })(BABYLON || (BABYLON = {}));
  72191. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  72192. "use strict";
  72193. var BABYLON;
  72194. (function (BABYLON) {
  72195. var TonemappingOperator;
  72196. (function (TonemappingOperator) {
  72197. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  72198. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  72199. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  72200. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  72201. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  72202. ;
  72203. var TonemapPostProcess = /** @class */ (function (_super) {
  72204. __extends(TonemapPostProcess, _super);
  72205. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  72206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72207. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72208. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  72209. _this._operator = _operator;
  72210. _this.exposureAdjustment = exposureAdjustment;
  72211. var defines = "#define ";
  72212. if (_this._operator === TonemappingOperator.Hable)
  72213. defines += "HABLE_TONEMAPPING";
  72214. else if (_this._operator === TonemappingOperator.Reinhard)
  72215. defines += "REINHARD_TONEMAPPING";
  72216. else if (_this._operator === TonemappingOperator.HejiDawson)
  72217. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  72218. else if (_this._operator === TonemappingOperator.Photographic)
  72219. defines += "PHOTOGRAPHIC_TONEMAPPING";
  72220. //sadly a second call to create the effect.
  72221. _this.updateEffect(defines);
  72222. _this.onApply = function (effect) {
  72223. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  72224. };
  72225. return _this;
  72226. }
  72227. return TonemapPostProcess;
  72228. }(BABYLON.PostProcess));
  72229. BABYLON.TonemapPostProcess = TonemapPostProcess;
  72230. })(BABYLON || (BABYLON = {}));
  72231. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  72232. "use strict";
  72233. var BABYLON;
  72234. (function (BABYLON) {
  72235. var DisplayPassPostProcess = /** @class */ (function (_super) {
  72236. __extends(DisplayPassPostProcess, _super);
  72237. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  72238. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  72239. }
  72240. return DisplayPassPostProcess;
  72241. }(BABYLON.PostProcess));
  72242. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  72243. })(BABYLON || (BABYLON = {}));
  72244. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  72245. "use strict";
  72246. var BABYLON;
  72247. (function (BABYLON) {
  72248. var HighlightsPostProcess = /** @class */ (function (_super) {
  72249. __extends(HighlightsPostProcess, _super);
  72250. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  72251. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72252. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  72253. }
  72254. return HighlightsPostProcess;
  72255. }(BABYLON.PostProcess));
  72256. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  72257. })(BABYLON || (BABYLON = {}));
  72258. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  72259. "use strict";
  72260. var BABYLON;
  72261. (function (BABYLON) {
  72262. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  72263. __extends(ImageProcessingPostProcess, _super);
  72264. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  72265. if (camera === void 0) { camera = null; }
  72266. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72267. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  72268. _this._fromLinearSpace = true;
  72269. /**
  72270. * Defines cache preventing GC.
  72271. */
  72272. _this._defines = {
  72273. IMAGEPROCESSING: false,
  72274. VIGNETTE: false,
  72275. VIGNETTEBLENDMODEMULTIPLY: false,
  72276. VIGNETTEBLENDMODEOPAQUE: false,
  72277. TONEMAPPING: false,
  72278. CONTRAST: false,
  72279. COLORCURVES: false,
  72280. COLORGRADING: false,
  72281. COLORGRADING3D: false,
  72282. FROMLINEARSPACE: false,
  72283. SAMPLER3DGREENDEPTH: false,
  72284. SAMPLER3DBGRMAP: false,
  72285. IMAGEPROCESSINGPOSTPROCESS: false,
  72286. EXPOSURE: false,
  72287. };
  72288. // Setup the configuration as forced by the constructor. This would then not force the
  72289. // scene materials output in linear space and let untouched the default forward pass.
  72290. if (imageProcessingConfiguration) {
  72291. imageProcessingConfiguration.applyByPostProcess = true;
  72292. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  72293. // This will cause the shader to be compiled
  72294. _this.fromLinearSpace = false;
  72295. }
  72296. else {
  72297. _this._attachImageProcessingConfiguration(null, true);
  72298. _this.imageProcessingConfiguration.applyByPostProcess = true;
  72299. }
  72300. _this.onApply = function (effect) {
  72301. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  72302. };
  72303. return _this;
  72304. }
  72305. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  72306. /**
  72307. * Gets the image processing configuration used either in this material.
  72308. */
  72309. get: function () {
  72310. return this._imageProcessingConfiguration;
  72311. },
  72312. /**
  72313. * Sets the Default image processing configuration used either in the this material.
  72314. *
  72315. * If sets to null, the scene one is in use.
  72316. */
  72317. set: function (value) {
  72318. this._attachImageProcessingConfiguration(value);
  72319. },
  72320. enumerable: true,
  72321. configurable: true
  72322. });
  72323. /**
  72324. * Attaches a new image processing configuration to the PBR Material.
  72325. * @param configuration
  72326. */
  72327. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  72328. var _this = this;
  72329. if (doNotBuild === void 0) { doNotBuild = false; }
  72330. if (configuration === this._imageProcessingConfiguration) {
  72331. return;
  72332. }
  72333. // Detaches observer.
  72334. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72335. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72336. }
  72337. // Pick the scene configuration if needed.
  72338. if (!configuration) {
  72339. var scene = null;
  72340. var engine = this.getEngine();
  72341. var camera = this.getCamera();
  72342. if (camera) {
  72343. scene = camera.getScene();
  72344. }
  72345. else if (engine && engine.scenes) {
  72346. var scenes = engine.scenes;
  72347. scene = scenes[scenes.length - 1];
  72348. }
  72349. else {
  72350. scene = BABYLON.Engine.LastCreatedScene;
  72351. }
  72352. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  72353. }
  72354. else {
  72355. this._imageProcessingConfiguration = configuration;
  72356. }
  72357. // Attaches observer.
  72358. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  72359. _this._updateParameters();
  72360. });
  72361. // Ensure the effect will be rebuilt.
  72362. if (!doNotBuild) {
  72363. this._updateParameters();
  72364. }
  72365. };
  72366. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  72367. /**
  72368. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72369. */
  72370. get: function () {
  72371. return this.imageProcessingConfiguration.colorCurves;
  72372. },
  72373. /**
  72374. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  72375. */
  72376. set: function (value) {
  72377. this.imageProcessingConfiguration.colorCurves = value;
  72378. },
  72379. enumerable: true,
  72380. configurable: true
  72381. });
  72382. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  72383. /**
  72384. * Gets wether the color curves effect is enabled.
  72385. */
  72386. get: function () {
  72387. return this.imageProcessingConfiguration.colorCurvesEnabled;
  72388. },
  72389. /**
  72390. * Sets wether the color curves effect is enabled.
  72391. */
  72392. set: function (value) {
  72393. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  72394. },
  72395. enumerable: true,
  72396. configurable: true
  72397. });
  72398. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  72399. /**
  72400. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72401. */
  72402. get: function () {
  72403. return this.imageProcessingConfiguration.colorGradingTexture;
  72404. },
  72405. /**
  72406. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  72407. */
  72408. set: function (value) {
  72409. this.imageProcessingConfiguration.colorGradingTexture = value;
  72410. },
  72411. enumerable: true,
  72412. configurable: true
  72413. });
  72414. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  72415. /**
  72416. * Gets wether the color grading effect is enabled.
  72417. */
  72418. get: function () {
  72419. return this.imageProcessingConfiguration.colorGradingEnabled;
  72420. },
  72421. /**
  72422. * Gets wether the color grading effect is enabled.
  72423. */
  72424. set: function (value) {
  72425. this.imageProcessingConfiguration.colorGradingEnabled = value;
  72426. },
  72427. enumerable: true,
  72428. configurable: true
  72429. });
  72430. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  72431. /**
  72432. * Gets exposure used in the effect.
  72433. */
  72434. get: function () {
  72435. return this.imageProcessingConfiguration.exposure;
  72436. },
  72437. /**
  72438. * Sets exposure used in the effect.
  72439. */
  72440. set: function (value) {
  72441. this.imageProcessingConfiguration.exposure = value;
  72442. },
  72443. enumerable: true,
  72444. configurable: true
  72445. });
  72446. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  72447. /**
  72448. * Gets wether tonemapping is enabled or not.
  72449. */
  72450. get: function () {
  72451. return this._imageProcessingConfiguration.toneMappingEnabled;
  72452. },
  72453. /**
  72454. * Sets wether tonemapping is enabled or not
  72455. */
  72456. set: function (value) {
  72457. this._imageProcessingConfiguration.toneMappingEnabled = value;
  72458. },
  72459. enumerable: true,
  72460. configurable: true
  72461. });
  72462. ;
  72463. ;
  72464. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  72465. /**
  72466. * Gets contrast used in the effect.
  72467. */
  72468. get: function () {
  72469. return this.imageProcessingConfiguration.contrast;
  72470. },
  72471. /**
  72472. * Sets contrast used in the effect.
  72473. */
  72474. set: function (value) {
  72475. this.imageProcessingConfiguration.contrast = value;
  72476. },
  72477. enumerable: true,
  72478. configurable: true
  72479. });
  72480. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  72481. /**
  72482. * Gets Vignette stretch size.
  72483. */
  72484. get: function () {
  72485. return this.imageProcessingConfiguration.vignetteStretch;
  72486. },
  72487. /**
  72488. * Sets Vignette stretch size.
  72489. */
  72490. set: function (value) {
  72491. this.imageProcessingConfiguration.vignetteStretch = value;
  72492. },
  72493. enumerable: true,
  72494. configurable: true
  72495. });
  72496. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  72497. /**
  72498. * Gets Vignette centre X Offset.
  72499. */
  72500. get: function () {
  72501. return this.imageProcessingConfiguration.vignetteCentreX;
  72502. },
  72503. /**
  72504. * Sets Vignette centre X Offset.
  72505. */
  72506. set: function (value) {
  72507. this.imageProcessingConfiguration.vignetteCentreX = value;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  72513. /**
  72514. * Gets Vignette centre Y Offset.
  72515. */
  72516. get: function () {
  72517. return this.imageProcessingConfiguration.vignetteCentreY;
  72518. },
  72519. /**
  72520. * Sets Vignette centre Y Offset.
  72521. */
  72522. set: function (value) {
  72523. this.imageProcessingConfiguration.vignetteCentreY = value;
  72524. },
  72525. enumerable: true,
  72526. configurable: true
  72527. });
  72528. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  72529. /**
  72530. * Gets Vignette weight or intensity of the vignette effect.
  72531. */
  72532. get: function () {
  72533. return this.imageProcessingConfiguration.vignetteWeight;
  72534. },
  72535. /**
  72536. * Sets Vignette weight or intensity of the vignette effect.
  72537. */
  72538. set: function (value) {
  72539. this.imageProcessingConfiguration.vignetteWeight = value;
  72540. },
  72541. enumerable: true,
  72542. configurable: true
  72543. });
  72544. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  72545. /**
  72546. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72547. * if vignetteEnabled is set to true.
  72548. */
  72549. get: function () {
  72550. return this.imageProcessingConfiguration.vignetteColor;
  72551. },
  72552. /**
  72553. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  72554. * if vignetteEnabled is set to true.
  72555. */
  72556. set: function (value) {
  72557. this.imageProcessingConfiguration.vignetteColor = value;
  72558. },
  72559. enumerable: true,
  72560. configurable: true
  72561. });
  72562. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  72563. /**
  72564. * Gets Camera field of view used by the Vignette effect.
  72565. */
  72566. get: function () {
  72567. return this.imageProcessingConfiguration.vignetteCameraFov;
  72568. },
  72569. /**
  72570. * Sets Camera field of view used by the Vignette effect.
  72571. */
  72572. set: function (value) {
  72573. this.imageProcessingConfiguration.vignetteCameraFov = value;
  72574. },
  72575. enumerable: true,
  72576. configurable: true
  72577. });
  72578. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  72579. /**
  72580. * Gets the vignette blend mode allowing different kind of effect.
  72581. */
  72582. get: function () {
  72583. return this.imageProcessingConfiguration.vignetteBlendMode;
  72584. },
  72585. /**
  72586. * Sets the vignette blend mode allowing different kind of effect.
  72587. */
  72588. set: function (value) {
  72589. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72590. },
  72591. enumerable: true,
  72592. configurable: true
  72593. });
  72594. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72595. /**
  72596. * Gets wether the vignette effect is enabled.
  72597. */
  72598. get: function () {
  72599. return this.imageProcessingConfiguration.vignetteEnabled;
  72600. },
  72601. /**
  72602. * Sets wether the vignette effect is enabled.
  72603. */
  72604. set: function (value) {
  72605. this.imageProcessingConfiguration.vignetteEnabled = value;
  72606. },
  72607. enumerable: true,
  72608. configurable: true
  72609. });
  72610. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72611. /**
  72612. * Gets wether the input of the processing is in Gamma or Linear Space.
  72613. */
  72614. get: function () {
  72615. return this._fromLinearSpace;
  72616. },
  72617. /**
  72618. * Sets wether the input of the processing is in Gamma or Linear Space.
  72619. */
  72620. set: function (value) {
  72621. if (this._fromLinearSpace === value) {
  72622. return;
  72623. }
  72624. this._fromLinearSpace = value;
  72625. this._updateParameters();
  72626. },
  72627. enumerable: true,
  72628. configurable: true
  72629. });
  72630. ImageProcessingPostProcess.prototype.getClassName = function () {
  72631. return "ImageProcessingPostProcess";
  72632. };
  72633. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72634. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72635. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72636. var defines = "";
  72637. for (var define in this._defines) {
  72638. if (this._defines[define]) {
  72639. defines += "#define " + define + ";\r\n";
  72640. }
  72641. }
  72642. var samplers = ["textureSampler"];
  72643. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72644. var uniforms = ["scale"];
  72645. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72646. this.updateEffect(defines, uniforms, samplers);
  72647. };
  72648. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72649. _super.prototype.dispose.call(this, camera);
  72650. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72651. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72652. }
  72653. this.imageProcessingConfiguration.applyByPostProcess = false;
  72654. };
  72655. __decorate([
  72656. BABYLON.serialize()
  72657. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72658. return ImageProcessingPostProcess;
  72659. }(BABYLON.PostProcess));
  72660. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72661. })(BABYLON || (BABYLON = {}));
  72662. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72663. "use strict";
  72664. var BABYLON;
  72665. (function (BABYLON) {
  72666. var Bone = /** @class */ (function (_super) {
  72667. __extends(Bone, _super);
  72668. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72669. if (parentBone === void 0) { parentBone = null; }
  72670. if (localMatrix === void 0) { localMatrix = null; }
  72671. if (restPose === void 0) { restPose = null; }
  72672. if (baseMatrix === void 0) { baseMatrix = null; }
  72673. if (index === void 0) { index = null; }
  72674. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72675. _this.name = name;
  72676. _this.children = new Array();
  72677. _this.animations = new Array();
  72678. // Set this value to map this bone to a different index in the transform matrices.
  72679. // Set this value to -1 to exclude the bone from the transform matrices.
  72680. _this._index = null;
  72681. _this._worldTransform = new BABYLON.Matrix();
  72682. _this._absoluteTransform = new BABYLON.Matrix();
  72683. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72684. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72685. _this._scaleVector = BABYLON.Vector3.One();
  72686. _this._negateScaleChildren = BABYLON.Vector3.One();
  72687. _this._scalingDeterminant = 1;
  72688. _this._skeleton = skeleton;
  72689. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72690. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72691. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72692. _this._index = index;
  72693. skeleton.bones.push(_this);
  72694. _this.setParent(parentBone, false);
  72695. _this._updateDifferenceMatrix();
  72696. return _this;
  72697. }
  72698. Object.defineProperty(Bone.prototype, "_matrix", {
  72699. get: function () {
  72700. return this._localMatrix;
  72701. },
  72702. set: function (val) {
  72703. if (this._localMatrix) {
  72704. this._localMatrix.copyFrom(val);
  72705. }
  72706. else {
  72707. this._localMatrix = val;
  72708. }
  72709. },
  72710. enumerable: true,
  72711. configurable: true
  72712. });
  72713. // Members
  72714. Bone.prototype.getSkeleton = function () {
  72715. return this._skeleton;
  72716. };
  72717. Bone.prototype.getParent = function () {
  72718. return this._parent;
  72719. };
  72720. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72721. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72722. if (this._parent === parent) {
  72723. return;
  72724. }
  72725. if (this._parent) {
  72726. var index = this._parent.children.indexOf(this);
  72727. if (index !== -1) {
  72728. this._parent.children.splice(index, 1);
  72729. }
  72730. }
  72731. this._parent = parent;
  72732. if (this._parent) {
  72733. this._parent.children.push(this);
  72734. }
  72735. if (updateDifferenceMatrix) {
  72736. this._updateDifferenceMatrix();
  72737. }
  72738. };
  72739. Bone.prototype.getLocalMatrix = function () {
  72740. return this._localMatrix;
  72741. };
  72742. Bone.prototype.getBaseMatrix = function () {
  72743. return this._baseMatrix;
  72744. };
  72745. Bone.prototype.getRestPose = function () {
  72746. return this._restPose;
  72747. };
  72748. Bone.prototype.returnToRest = function () {
  72749. this.updateMatrix(this._restPose.clone());
  72750. };
  72751. Bone.prototype.getWorldMatrix = function () {
  72752. return this._worldTransform;
  72753. };
  72754. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72755. return this._invertedAbsoluteTransform;
  72756. };
  72757. Bone.prototype.getAbsoluteTransform = function () {
  72758. return this._absoluteTransform;
  72759. };
  72760. Object.defineProperty(Bone.prototype, "position", {
  72761. // Properties (matches AbstractMesh properties)
  72762. get: function () {
  72763. return this.getPosition();
  72764. },
  72765. set: function (newPosition) {
  72766. this.setPosition(newPosition);
  72767. },
  72768. enumerable: true,
  72769. configurable: true
  72770. });
  72771. Object.defineProperty(Bone.prototype, "rotation", {
  72772. get: function () {
  72773. return this.getRotation();
  72774. },
  72775. set: function (newRotation) {
  72776. this.setRotation(newRotation);
  72777. },
  72778. enumerable: true,
  72779. configurable: true
  72780. });
  72781. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72782. get: function () {
  72783. return this.getRotationQuaternion();
  72784. },
  72785. set: function (newRotation) {
  72786. this.setRotationQuaternion(newRotation);
  72787. },
  72788. enumerable: true,
  72789. configurable: true
  72790. });
  72791. Object.defineProperty(Bone.prototype, "scaling", {
  72792. get: function () {
  72793. return this.getScale();
  72794. },
  72795. set: function (newScaling) {
  72796. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72797. },
  72798. enumerable: true,
  72799. configurable: true
  72800. });
  72801. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72802. /**
  72803. * Gets the animation properties override
  72804. */
  72805. get: function () {
  72806. return this._skeleton.animationPropertiesOverride;
  72807. },
  72808. enumerable: true,
  72809. configurable: true
  72810. });
  72811. // Methods
  72812. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72813. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72814. this._baseMatrix = matrix.clone();
  72815. this._localMatrix = matrix.clone();
  72816. this._skeleton._markAsDirty();
  72817. if (updateDifferenceMatrix) {
  72818. this._updateDifferenceMatrix();
  72819. }
  72820. };
  72821. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72822. if (!rootMatrix) {
  72823. rootMatrix = this._baseMatrix;
  72824. }
  72825. if (this._parent) {
  72826. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72827. }
  72828. else {
  72829. this._absoluteTransform.copyFrom(rootMatrix);
  72830. }
  72831. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72832. for (var index = 0; index < this.children.length; index++) {
  72833. this.children[index]._updateDifferenceMatrix();
  72834. }
  72835. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72836. };
  72837. Bone.prototype.markAsDirty = function () {
  72838. this._currentRenderId++;
  72839. this._childRenderId++;
  72840. this._skeleton._markAsDirty();
  72841. };
  72842. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72843. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72844. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72845. // all animation may be coming from a library skeleton, so may need to create animation
  72846. if (this.animations.length === 0) {
  72847. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72848. this.animations[0].setKeys([]);
  72849. }
  72850. // get animation info / verify there is such a range from the source bone
  72851. var sourceRange = source.animations[0].getRange(rangeName);
  72852. if (!sourceRange) {
  72853. return false;
  72854. }
  72855. var from = sourceRange.from;
  72856. var to = sourceRange.to;
  72857. var sourceKeys = source.animations[0].getKeys();
  72858. // rescaling prep
  72859. var sourceBoneLength = source.length;
  72860. var sourceParent = source.getParent();
  72861. var parent = this.getParent();
  72862. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72863. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72864. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72865. var destKeys = this.animations[0].getKeys();
  72866. // loop vars declaration
  72867. var orig;
  72868. var origTranslation;
  72869. var mat;
  72870. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72871. orig = sourceKeys[key];
  72872. if (orig.frame >= from && orig.frame <= to) {
  72873. if (rescaleAsRequired) {
  72874. mat = orig.value.clone();
  72875. // scale based on parent ratio, when bone has parent
  72876. if (parentScalingReqd) {
  72877. origTranslation = mat.getTranslation();
  72878. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72879. // scale based on skeleton dimension ratio when root bone, and value is passed
  72880. }
  72881. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72882. origTranslation = mat.getTranslation();
  72883. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72884. // use original when root bone, and no data for skelDimensionsRatio
  72885. }
  72886. else {
  72887. mat = orig.value;
  72888. }
  72889. }
  72890. else {
  72891. mat = orig.value;
  72892. }
  72893. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72894. }
  72895. }
  72896. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72897. return true;
  72898. };
  72899. /**
  72900. * Translate the bone in local or world space.
  72901. * @param vec The amount to translate the bone.
  72902. * @param space The space that the translation is in.
  72903. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72904. */
  72905. Bone.prototype.translate = function (vec, space, mesh) {
  72906. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72907. var lm = this.getLocalMatrix();
  72908. if (space == BABYLON.Space.LOCAL) {
  72909. lm.m[12] += vec.x;
  72910. lm.m[13] += vec.y;
  72911. lm.m[14] += vec.z;
  72912. }
  72913. else {
  72914. var wm = null;
  72915. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72916. if (mesh) {
  72917. wm = mesh.getWorldMatrix();
  72918. }
  72919. this._skeleton.computeAbsoluteTransforms();
  72920. var tmat = Bone._tmpMats[0];
  72921. var tvec = Bone._tmpVecs[0];
  72922. if (this._parent) {
  72923. if (mesh && wm) {
  72924. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72925. tmat.multiplyToRef(wm, tmat);
  72926. }
  72927. else {
  72928. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72929. }
  72930. }
  72931. tmat.m[12] = 0;
  72932. tmat.m[13] = 0;
  72933. tmat.m[14] = 0;
  72934. tmat.invert();
  72935. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72936. lm.m[12] += tvec.x;
  72937. lm.m[13] += tvec.y;
  72938. lm.m[14] += tvec.z;
  72939. }
  72940. this.markAsDirty();
  72941. };
  72942. /**
  72943. * Set the postion of the bone in local or world space.
  72944. * @param position The position to set the bone.
  72945. * @param space The space that the position is in.
  72946. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72947. */
  72948. Bone.prototype.setPosition = function (position, space, mesh) {
  72949. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72950. var lm = this.getLocalMatrix();
  72951. if (space == BABYLON.Space.LOCAL) {
  72952. lm.m[12] = position.x;
  72953. lm.m[13] = position.y;
  72954. lm.m[14] = position.z;
  72955. }
  72956. else {
  72957. var wm = null;
  72958. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72959. if (mesh) {
  72960. wm = mesh.getWorldMatrix();
  72961. }
  72962. this._skeleton.computeAbsoluteTransforms();
  72963. var tmat = Bone._tmpMats[0];
  72964. var vec = Bone._tmpVecs[0];
  72965. if (this._parent) {
  72966. if (mesh && wm) {
  72967. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72968. tmat.multiplyToRef(wm, tmat);
  72969. }
  72970. else {
  72971. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72972. }
  72973. }
  72974. tmat.invert();
  72975. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72976. lm.m[12] = vec.x;
  72977. lm.m[13] = vec.y;
  72978. lm.m[14] = vec.z;
  72979. }
  72980. this.markAsDirty();
  72981. };
  72982. /**
  72983. * Set the absolute postion of the bone (world space).
  72984. * @param position The position to set the bone.
  72985. * @param mesh The mesh that this bone is attached to.
  72986. */
  72987. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72988. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72989. };
  72990. /**
  72991. * Set the scale of the bone on the x, y and z axes.
  72992. * @param x The scale of the bone on the x axis.
  72993. * @param x The scale of the bone on the y axis.
  72994. * @param z The scale of the bone on the z axis.
  72995. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72996. */
  72997. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72998. if (scaleChildren === void 0) { scaleChildren = false; }
  72999. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  73000. if (!scaleChildren) {
  73001. this._negateScaleChildren.x = 1 / x;
  73002. this._negateScaleChildren.y = 1 / y;
  73003. this._negateScaleChildren.z = 1 / z;
  73004. }
  73005. this._syncScaleVector();
  73006. }
  73007. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  73008. };
  73009. /**
  73010. * Scale the bone on the x, y and z axes.
  73011. * @param x The amount to scale the bone on the x axis.
  73012. * @param x The amount to scale the bone on the y axis.
  73013. * @param z The amount to scale the bone on the z axis.
  73014. * @param scaleChildren Set this to true if children of the bone should be scaled.
  73015. */
  73016. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  73017. if (scaleChildren === void 0) { scaleChildren = false; }
  73018. var locMat = this.getLocalMatrix();
  73019. var origLocMat = Bone._tmpMats[0];
  73020. origLocMat.copyFrom(locMat);
  73021. var origLocMatInv = Bone._tmpMats[1];
  73022. origLocMatInv.copyFrom(origLocMat);
  73023. origLocMatInv.invert();
  73024. var scaleMat = Bone._tmpMats[2];
  73025. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  73026. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  73027. this._scaleVector.x *= x;
  73028. this._scaleVector.y *= y;
  73029. this._scaleVector.z *= z;
  73030. locMat.multiplyToRef(origLocMatInv, locMat);
  73031. locMat.multiplyToRef(scaleMat, locMat);
  73032. locMat.multiplyToRef(origLocMat, locMat);
  73033. var parent = this.getParent();
  73034. if (parent) {
  73035. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  73036. }
  73037. else {
  73038. this.getAbsoluteTransform().copyFrom(locMat);
  73039. }
  73040. var len = this.children.length;
  73041. scaleMat.invert();
  73042. for (var i = 0; i < len; i++) {
  73043. var child = this.children[i];
  73044. var cm = child.getLocalMatrix();
  73045. cm.multiplyToRef(scaleMat, cm);
  73046. var lm = child.getLocalMatrix();
  73047. lm.m[12] *= x;
  73048. lm.m[13] *= y;
  73049. lm.m[14] *= z;
  73050. }
  73051. this.computeAbsoluteTransforms();
  73052. if (scaleChildren) {
  73053. for (var i = 0; i < len; i++) {
  73054. this.children[i].scale(x, y, z, scaleChildren);
  73055. }
  73056. }
  73057. this.markAsDirty();
  73058. };
  73059. /**
  73060. * Set the yaw, pitch, and roll of the bone in local or world space.
  73061. * @param yaw The rotation of the bone on the y axis.
  73062. * @param pitch The rotation of the bone on the x axis.
  73063. * @param roll The rotation of the bone on the z axis.
  73064. * @param space The space that the axes of rotation are in.
  73065. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73066. */
  73067. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  73068. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73069. var rotMat = Bone._tmpMats[0];
  73070. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  73071. var rotMatInv = Bone._tmpMats[1];
  73072. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73073. rotMatInv.multiplyToRef(rotMat, rotMat);
  73074. this._rotateWithMatrix(rotMat, space, mesh);
  73075. };
  73076. /**
  73077. * Rotate the bone on an axis in local or world space.
  73078. * @param axis The axis to rotate the bone on.
  73079. * @param amount The amount to rotate the bone.
  73080. * @param space The space that the axis is in.
  73081. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73082. */
  73083. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  73084. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73085. var rmat = Bone._tmpMats[0];
  73086. rmat.m[12] = 0;
  73087. rmat.m[13] = 0;
  73088. rmat.m[14] = 0;
  73089. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  73090. this._rotateWithMatrix(rmat, space, mesh);
  73091. };
  73092. /**
  73093. * Set the rotation of the bone to a particular axis angle in local or world space.
  73094. * @param axis The axis to rotate the bone on.
  73095. * @param angle The angle that the bone should be rotated to.
  73096. * @param space The space that the axis is in.
  73097. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73098. */
  73099. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  73100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73101. var rotMat = Bone._tmpMats[0];
  73102. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  73103. var rotMatInv = Bone._tmpMats[1];
  73104. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73105. rotMatInv.multiplyToRef(rotMat, rotMat);
  73106. this._rotateWithMatrix(rotMat, space, mesh);
  73107. };
  73108. /**
  73109. * Set the euler rotation of the bone in local of world space.
  73110. * @param rotation The euler rotation that the bone should be set to.
  73111. * @param space The space that the rotation is in.
  73112. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73113. */
  73114. Bone.prototype.setRotation = function (rotation, space, mesh) {
  73115. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73116. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  73117. };
  73118. /**
  73119. * Set the quaternion rotation of the bone in local of world space.
  73120. * @param quat The quaternion rotation that the bone should be set to.
  73121. * @param space The space that the rotation is in.
  73122. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73123. */
  73124. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  73125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73126. var rotMatInv = Bone._tmpMats[0];
  73127. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73128. var rotMat = Bone._tmpMats[1];
  73129. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  73130. rotMatInv.multiplyToRef(rotMat, rotMat);
  73131. this._rotateWithMatrix(rotMat, space, mesh);
  73132. };
  73133. /**
  73134. * Set the rotation matrix of the bone in local of world space.
  73135. * @param rotMat The rotation matrix that the bone should be set to.
  73136. * @param space The space that the rotation is in.
  73137. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73138. */
  73139. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  73140. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73141. var rotMatInv = Bone._tmpMats[0];
  73142. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  73143. var rotMat2 = Bone._tmpMats[1];
  73144. rotMat2.copyFrom(rotMat);
  73145. rotMatInv.multiplyToRef(rotMat, rotMat2);
  73146. this._rotateWithMatrix(rotMat2, space, mesh);
  73147. };
  73148. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  73149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73150. var lmat = this.getLocalMatrix();
  73151. var lx = lmat.m[12];
  73152. var ly = lmat.m[13];
  73153. var lz = lmat.m[14];
  73154. var parent = this.getParent();
  73155. var parentScale = Bone._tmpMats[3];
  73156. var parentScaleInv = Bone._tmpMats[4];
  73157. if (parent) {
  73158. if (space == BABYLON.Space.WORLD) {
  73159. if (mesh) {
  73160. parentScale.copyFrom(mesh.getWorldMatrix());
  73161. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  73162. }
  73163. else {
  73164. parentScale.copyFrom(parent.getAbsoluteTransform());
  73165. }
  73166. }
  73167. else {
  73168. parentScale = parent._scaleMatrix;
  73169. }
  73170. parentScaleInv.copyFrom(parentScale);
  73171. parentScaleInv.invert();
  73172. lmat.multiplyToRef(parentScale, lmat);
  73173. lmat.multiplyToRef(rmat, lmat);
  73174. lmat.multiplyToRef(parentScaleInv, lmat);
  73175. }
  73176. else {
  73177. if (space == BABYLON.Space.WORLD && mesh) {
  73178. parentScale.copyFrom(mesh.getWorldMatrix());
  73179. parentScaleInv.copyFrom(parentScale);
  73180. parentScaleInv.invert();
  73181. lmat.multiplyToRef(parentScale, lmat);
  73182. lmat.multiplyToRef(rmat, lmat);
  73183. lmat.multiplyToRef(parentScaleInv, lmat);
  73184. }
  73185. else {
  73186. lmat.multiplyToRef(rmat, lmat);
  73187. }
  73188. }
  73189. lmat.m[12] = lx;
  73190. lmat.m[13] = ly;
  73191. lmat.m[14] = lz;
  73192. this.computeAbsoluteTransforms();
  73193. this.markAsDirty();
  73194. };
  73195. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  73196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73197. if (space == BABYLON.Space.WORLD) {
  73198. var scaleMatrix = Bone._tmpMats[2];
  73199. scaleMatrix.copyFrom(this._scaleMatrix);
  73200. rotMatInv.copyFrom(this.getAbsoluteTransform());
  73201. if (mesh) {
  73202. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  73203. var meshScale = Bone._tmpMats[3];
  73204. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  73205. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  73206. }
  73207. rotMatInv.invert();
  73208. scaleMatrix.m[0] *= this._scalingDeterminant;
  73209. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73210. }
  73211. else {
  73212. rotMatInv.copyFrom(this.getLocalMatrix());
  73213. rotMatInv.invert();
  73214. var scaleMatrix = Bone._tmpMats[2];
  73215. scaleMatrix.copyFrom(this._scaleMatrix);
  73216. if (this._parent) {
  73217. var pscaleMatrix = Bone._tmpMats[3];
  73218. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  73219. pscaleMatrix.invert();
  73220. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  73221. }
  73222. else {
  73223. scaleMatrix.m[0] *= this._scalingDeterminant;
  73224. }
  73225. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  73226. }
  73227. };
  73228. /**
  73229. * Get the scale of the bone
  73230. * @returns the scale of the bone
  73231. */
  73232. Bone.prototype.getScale = function () {
  73233. return this._scaleVector.clone();
  73234. };
  73235. /**
  73236. * Copy the scale of the bone to a vector3.
  73237. * @param result The vector3 to copy the scale to
  73238. */
  73239. Bone.prototype.getScaleToRef = function (result) {
  73240. result.copyFrom(this._scaleVector);
  73241. };
  73242. /**
  73243. * Get the position of the bone in local or world space.
  73244. * @param space The space that the returned position is in.
  73245. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73246. * @returns The position of the bone
  73247. */
  73248. Bone.prototype.getPosition = function (space, mesh) {
  73249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73250. if (mesh === void 0) { mesh = null; }
  73251. var pos = BABYLON.Vector3.Zero();
  73252. this.getPositionToRef(space, mesh, pos);
  73253. return pos;
  73254. };
  73255. /**
  73256. * Copy the position of the bone to a vector3 in local or world space.
  73257. * @param space The space that the returned position is in.
  73258. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73259. * @param result The vector3 to copy the position to.
  73260. */
  73261. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  73262. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73263. if (space == BABYLON.Space.LOCAL) {
  73264. var lm = this.getLocalMatrix();
  73265. result.x = lm.m[12];
  73266. result.y = lm.m[13];
  73267. result.z = lm.m[14];
  73268. }
  73269. else {
  73270. var wm = null;
  73271. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73272. if (mesh) {
  73273. wm = mesh.getWorldMatrix();
  73274. }
  73275. this._skeleton.computeAbsoluteTransforms();
  73276. var tmat = Bone._tmpMats[0];
  73277. if (mesh && wm) {
  73278. tmat.copyFrom(this.getAbsoluteTransform());
  73279. tmat.multiplyToRef(wm, tmat);
  73280. }
  73281. else {
  73282. tmat = this.getAbsoluteTransform();
  73283. }
  73284. result.x = tmat.m[12];
  73285. result.y = tmat.m[13];
  73286. result.z = tmat.m[14];
  73287. }
  73288. };
  73289. /**
  73290. * Get the absolute position of the bone (world space).
  73291. * @param mesh The mesh that this bone is attached to.
  73292. * @returns The absolute position of the bone
  73293. */
  73294. Bone.prototype.getAbsolutePosition = function (mesh) {
  73295. if (mesh === void 0) { mesh = null; }
  73296. var pos = BABYLON.Vector3.Zero();
  73297. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  73298. return pos;
  73299. };
  73300. /**
  73301. * Copy the absolute position of the bone (world space) to the result param.
  73302. * @param mesh The mesh that this bone is attached to.
  73303. * @param result The vector3 to copy the absolute position to.
  73304. */
  73305. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  73306. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  73307. };
  73308. /**
  73309. * Compute the absolute transforms of this bone and its children.
  73310. */
  73311. Bone.prototype.computeAbsoluteTransforms = function () {
  73312. if (this._parent) {
  73313. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  73314. }
  73315. else {
  73316. this._absoluteTransform.copyFrom(this._localMatrix);
  73317. var poseMatrix = this._skeleton.getPoseMatrix();
  73318. if (poseMatrix) {
  73319. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  73320. }
  73321. }
  73322. var children = this.children;
  73323. var len = children.length;
  73324. for (var i = 0; i < len; i++) {
  73325. children[i].computeAbsoluteTransforms();
  73326. }
  73327. };
  73328. Bone.prototype._syncScaleVector = function () {
  73329. var lm = this.getLocalMatrix();
  73330. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  73331. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  73332. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  73333. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  73334. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  73335. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  73336. this._scaleVector.x = xs * Math.sqrt(xsq);
  73337. this._scaleVector.y = ys * Math.sqrt(ysq);
  73338. this._scaleVector.z = zs * Math.sqrt(zsq);
  73339. if (this._parent) {
  73340. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  73341. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  73342. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  73343. }
  73344. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  73345. };
  73346. /**
  73347. * Get the world direction from an axis that is in the local space of the bone.
  73348. * @param localAxis The local direction that is used to compute the world direction.
  73349. * @param mesh The mesh that this bone is attached to.
  73350. * @returns The world direction
  73351. */
  73352. Bone.prototype.getDirection = function (localAxis, mesh) {
  73353. if (mesh === void 0) { mesh = null; }
  73354. var result = BABYLON.Vector3.Zero();
  73355. this.getDirectionToRef(localAxis, mesh, result);
  73356. return result;
  73357. };
  73358. /**
  73359. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  73360. * @param localAxis The local direction that is used to compute the world direction.
  73361. * @param mesh The mesh that this bone is attached to.
  73362. * @param result The vector3 that the world direction will be copied to.
  73363. */
  73364. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  73365. if (mesh === void 0) { mesh = null; }
  73366. var wm = null;
  73367. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73368. if (mesh) {
  73369. wm = mesh.getWorldMatrix();
  73370. }
  73371. this._skeleton.computeAbsoluteTransforms();
  73372. var mat = Bone._tmpMats[0];
  73373. mat.copyFrom(this.getAbsoluteTransform());
  73374. if (mesh && wm) {
  73375. mat.multiplyToRef(wm, mat);
  73376. }
  73377. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  73378. result.normalize();
  73379. };
  73380. /**
  73381. * Get the euler rotation of the bone in local or world space.
  73382. * @param space The space that the rotation should be in.
  73383. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73384. * @returns The euler rotation
  73385. */
  73386. Bone.prototype.getRotation = function (space, mesh) {
  73387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73388. if (mesh === void 0) { mesh = null; }
  73389. var result = BABYLON.Vector3.Zero();
  73390. this.getRotationToRef(space, mesh, result);
  73391. return result;
  73392. };
  73393. /**
  73394. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  73395. * @param space The space that the rotation should be in.
  73396. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73397. * @param result The vector3 that the rotation should be copied to.
  73398. */
  73399. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  73400. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73401. if (mesh === void 0) { mesh = null; }
  73402. var quat = Bone._tmpQuat;
  73403. this.getRotationQuaternionToRef(space, mesh, quat);
  73404. quat.toEulerAnglesToRef(result);
  73405. };
  73406. /**
  73407. * Get the quaternion rotation of the bone in either local or world space.
  73408. * @param space The space that the rotation should be in.
  73409. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73410. * @returns The quaternion rotation
  73411. */
  73412. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  73413. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73414. if (mesh === void 0) { mesh = null; }
  73415. var result = BABYLON.Quaternion.Identity();
  73416. this.getRotationQuaternionToRef(space, mesh, result);
  73417. return result;
  73418. };
  73419. /**
  73420. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  73421. * @param space The space that the rotation should be in.
  73422. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73423. * @param result The quaternion that the rotation should be copied to.
  73424. */
  73425. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  73426. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73427. if (mesh === void 0) { mesh = null; }
  73428. if (space == BABYLON.Space.LOCAL) {
  73429. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73430. }
  73431. else {
  73432. var mat = Bone._tmpMats[0];
  73433. var amat = this.getAbsoluteTransform();
  73434. if (mesh) {
  73435. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73436. }
  73437. else {
  73438. mat.copyFrom(amat);
  73439. }
  73440. mat.m[0] *= this._scalingDeterminant;
  73441. mat.m[1] *= this._scalingDeterminant;
  73442. mat.m[2] *= this._scalingDeterminant;
  73443. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  73444. }
  73445. };
  73446. /**
  73447. * Get the rotation matrix of the bone in local or world space.
  73448. * @param space The space that the rotation should be in.
  73449. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73450. * @returns The rotation matrix
  73451. */
  73452. Bone.prototype.getRotationMatrix = function (space, mesh) {
  73453. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73454. var result = BABYLON.Matrix.Identity();
  73455. this.getRotationMatrixToRef(space, mesh, result);
  73456. return result;
  73457. };
  73458. /**
  73459. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  73460. * @param space The space that the rotation should be in.
  73461. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  73462. * @param result The quaternion that the rotation should be copied to.
  73463. */
  73464. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  73465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  73466. if (space == BABYLON.Space.LOCAL) {
  73467. this.getLocalMatrix().getRotationMatrixToRef(result);
  73468. }
  73469. else {
  73470. var mat = Bone._tmpMats[0];
  73471. var amat = this.getAbsoluteTransform();
  73472. if (mesh) {
  73473. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  73474. }
  73475. else {
  73476. mat.copyFrom(amat);
  73477. }
  73478. mat.m[0] *= this._scalingDeterminant;
  73479. mat.m[1] *= this._scalingDeterminant;
  73480. mat.m[2] *= this._scalingDeterminant;
  73481. mat.getRotationMatrixToRef(result);
  73482. }
  73483. };
  73484. /**
  73485. * Get the world position of a point that is in the local space of the bone.
  73486. * @param position The local position
  73487. * @param mesh The mesh that this bone is attached to.
  73488. * @returns The world position
  73489. */
  73490. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  73491. if (mesh === void 0) { mesh = null; }
  73492. var result = BABYLON.Vector3.Zero();
  73493. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  73494. return result;
  73495. };
  73496. /**
  73497. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  73498. * @param position The local position
  73499. * @param mesh The mesh that this bone is attached to.
  73500. * @param result The vector3 that the world position should be copied to.
  73501. */
  73502. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  73503. if (mesh === void 0) { mesh = null; }
  73504. var wm = null;
  73505. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73506. if (mesh) {
  73507. wm = mesh.getWorldMatrix();
  73508. }
  73509. this._skeleton.computeAbsoluteTransforms();
  73510. var tmat = Bone._tmpMats[0];
  73511. if (mesh && wm) {
  73512. tmat.copyFrom(this.getAbsoluteTransform());
  73513. tmat.multiplyToRef(wm, tmat);
  73514. }
  73515. else {
  73516. tmat = this.getAbsoluteTransform();
  73517. }
  73518. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73519. };
  73520. /**
  73521. * Get the local position of a point that is in world space.
  73522. * @param position The world position
  73523. * @param mesh The mesh that this bone is attached to.
  73524. * @returns The local position
  73525. */
  73526. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  73527. if (mesh === void 0) { mesh = null; }
  73528. var result = BABYLON.Vector3.Zero();
  73529. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  73530. return result;
  73531. };
  73532. /**
  73533. * Get the local position of a point that is in world space and copy it to the result param.
  73534. * @param position The world position
  73535. * @param mesh The mesh that this bone is attached to.
  73536. * @param result The vector3 that the local position should be copied to.
  73537. */
  73538. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73539. if (mesh === void 0) { mesh = null; }
  73540. var wm = null;
  73541. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73542. if (mesh) {
  73543. wm = mesh.getWorldMatrix();
  73544. }
  73545. this._skeleton.computeAbsoluteTransforms();
  73546. var tmat = Bone._tmpMats[0];
  73547. tmat.copyFrom(this.getAbsoluteTransform());
  73548. if (mesh && wm) {
  73549. tmat.multiplyToRef(wm, tmat);
  73550. }
  73551. tmat.invert();
  73552. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73553. };
  73554. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73555. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73556. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73557. return Bone;
  73558. }(BABYLON.Node));
  73559. BABYLON.Bone = Bone;
  73560. })(BABYLON || (BABYLON = {}));
  73561. //# sourceMappingURL=babylon.bone.js.map
  73562. "use strict";
  73563. var BABYLON;
  73564. (function (BABYLON) {
  73565. var BoneIKController = /** @class */ (function () {
  73566. function BoneIKController(mesh, bone, options) {
  73567. this.targetPosition = BABYLON.Vector3.Zero();
  73568. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73569. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73570. this.poleAngle = 0;
  73571. this.slerpAmount = 1;
  73572. this._bone1Quat = BABYLON.Quaternion.Identity();
  73573. this._bone1Mat = BABYLON.Matrix.Identity();
  73574. this._bone2Ang = Math.PI;
  73575. this._maxAngle = Math.PI;
  73576. this._rightHandedSystem = false;
  73577. this._bendAxis = BABYLON.Vector3.Right();
  73578. this._slerping = false;
  73579. this._adjustRoll = 0;
  73580. this._bone2 = bone;
  73581. this._bone1 = bone.getParent();
  73582. if (!this._bone1) {
  73583. return;
  73584. }
  73585. this.mesh = mesh;
  73586. var bonePos = bone.getPosition();
  73587. if (bone.getAbsoluteTransform().determinant() > 0) {
  73588. this._rightHandedSystem = true;
  73589. this._bendAxis.x = 0;
  73590. this._bendAxis.y = 0;
  73591. this._bendAxis.z = -1;
  73592. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73593. this._adjustRoll = Math.PI * .5;
  73594. this._bendAxis.z = 1;
  73595. }
  73596. }
  73597. if (this._bone1.length) {
  73598. var boneScale1 = this._bone1.getScale();
  73599. var boneScale2 = this._bone2.getScale();
  73600. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73601. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73602. }
  73603. else if (this._bone1.children[0]) {
  73604. mesh.computeWorldMatrix(true);
  73605. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73606. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73607. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73608. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73609. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73610. }
  73611. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73612. this.maxAngle = Math.PI;
  73613. if (options) {
  73614. if (options.targetMesh) {
  73615. this.targetMesh = options.targetMesh;
  73616. this.targetMesh.computeWorldMatrix(true);
  73617. }
  73618. if (options.poleTargetMesh) {
  73619. this.poleTargetMesh = options.poleTargetMesh;
  73620. this.poleTargetMesh.computeWorldMatrix(true);
  73621. }
  73622. else if (options.poleTargetBone) {
  73623. this.poleTargetBone = options.poleTargetBone;
  73624. }
  73625. else if (this._bone1.getParent()) {
  73626. this.poleTargetBone = this._bone1.getParent();
  73627. }
  73628. if (options.poleTargetLocalOffset) {
  73629. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73630. }
  73631. if (options.poleAngle) {
  73632. this.poleAngle = options.poleAngle;
  73633. }
  73634. if (options.bendAxis) {
  73635. this._bendAxis.copyFrom(options.bendAxis);
  73636. }
  73637. if (options.maxAngle) {
  73638. this.maxAngle = options.maxAngle;
  73639. }
  73640. if (options.slerpAmount) {
  73641. this.slerpAmount = options.slerpAmount;
  73642. }
  73643. }
  73644. }
  73645. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73646. get: function () {
  73647. return this._maxAngle;
  73648. },
  73649. set: function (value) {
  73650. this._setMaxAngle(value);
  73651. },
  73652. enumerable: true,
  73653. configurable: true
  73654. });
  73655. BoneIKController.prototype._setMaxAngle = function (ang) {
  73656. if (ang < 0) {
  73657. ang = 0;
  73658. }
  73659. if (ang > Math.PI || ang == undefined) {
  73660. ang = Math.PI;
  73661. }
  73662. this._maxAngle = ang;
  73663. var a = this._bone1Length;
  73664. var b = this._bone2Length;
  73665. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73666. };
  73667. BoneIKController.prototype.update = function () {
  73668. var bone1 = this._bone1;
  73669. if (!bone1) {
  73670. return;
  73671. }
  73672. var target = this.targetPosition;
  73673. var poleTarget = this.poleTargetPosition;
  73674. var mat1 = BoneIKController._tmpMats[0];
  73675. var mat2 = BoneIKController._tmpMats[1];
  73676. if (this.targetMesh) {
  73677. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73678. }
  73679. if (this.poleTargetBone) {
  73680. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73681. }
  73682. else if (this.poleTargetMesh) {
  73683. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73684. }
  73685. var bonePos = BoneIKController._tmpVecs[0];
  73686. var zaxis = BoneIKController._tmpVecs[1];
  73687. var xaxis = BoneIKController._tmpVecs[2];
  73688. var yaxis = BoneIKController._tmpVecs[3];
  73689. var upAxis = BoneIKController._tmpVecs[4];
  73690. var _tmpQuat = BoneIKController._tmpQuat;
  73691. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73692. poleTarget.subtractToRef(bonePos, upAxis);
  73693. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73694. upAxis.y = 1;
  73695. }
  73696. else {
  73697. upAxis.normalize();
  73698. }
  73699. target.subtractToRef(bonePos, yaxis);
  73700. yaxis.normalize();
  73701. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73702. zaxis.normalize();
  73703. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73704. xaxis.normalize();
  73705. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73706. var a = this._bone1Length;
  73707. var b = this._bone2Length;
  73708. var c = BABYLON.Vector3.Distance(bonePos, target);
  73709. if (this._maxReach > 0) {
  73710. c = Math.min(this._maxReach, c);
  73711. }
  73712. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73713. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73714. if (acosa > 1) {
  73715. acosa = 1;
  73716. }
  73717. if (acosb > 1) {
  73718. acosb = 1;
  73719. }
  73720. if (acosa < -1) {
  73721. acosa = -1;
  73722. }
  73723. if (acosb < -1) {
  73724. acosb = -1;
  73725. }
  73726. var angA = Math.acos(acosa);
  73727. var angB = Math.acos(acosb);
  73728. var angC = -angA - angB;
  73729. if (this._rightHandedSystem) {
  73730. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73731. mat2.multiplyToRef(mat1, mat1);
  73732. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73733. mat2.multiplyToRef(mat1, mat1);
  73734. }
  73735. else {
  73736. var _tmpVec = BoneIKController._tmpVecs[5];
  73737. _tmpVec.copyFrom(this._bendAxis);
  73738. _tmpVec.x *= -1;
  73739. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73740. mat2.multiplyToRef(mat1, mat1);
  73741. }
  73742. if (this.poleAngle) {
  73743. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73744. mat1.multiplyToRef(mat2, mat1);
  73745. }
  73746. if (this._bone1) {
  73747. if (this.slerpAmount < 1) {
  73748. if (!this._slerping) {
  73749. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73750. }
  73751. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73752. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73753. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73754. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73755. this._slerping = true;
  73756. }
  73757. else {
  73758. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73759. this._bone1Mat.copyFrom(mat1);
  73760. this._slerping = false;
  73761. }
  73762. }
  73763. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73764. this._bone2Ang = angC;
  73765. };
  73766. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73767. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73768. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73769. return BoneIKController;
  73770. }());
  73771. BABYLON.BoneIKController = BoneIKController;
  73772. })(BABYLON || (BABYLON = {}));
  73773. //# sourceMappingURL=babylon.boneIKController.js.map
  73774. "use strict";
  73775. var BABYLON;
  73776. (function (BABYLON) {
  73777. var BoneLookController = /** @class */ (function () {
  73778. /**
  73779. * Create a BoneLookController
  73780. * @param mesh the mesh that the bone belongs to
  73781. * @param bone the bone that will be looking to the target
  73782. * @param target the target Vector3 to look at
  73783. * @param settings optional settings:
  73784. * - maxYaw: the maximum angle the bone will yaw to
  73785. * - minYaw: the minimum angle the bone will yaw to
  73786. * - maxPitch: the maximum angle the bone will pitch to
  73787. * - minPitch: the minimum angle the bone will yaw to
  73788. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73789. * - upAxis: the up axis of the coordinate system
  73790. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73791. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73792. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73793. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73794. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73795. * - adjustRoll: used to make an adjustment to the roll of the bone
  73796. **/
  73797. function BoneLookController(mesh, bone, target, options) {
  73798. /**
  73799. * The up axis of the coordinate system that is used when the bone is rotated.
  73800. */
  73801. this.upAxis = BABYLON.Vector3.Up();
  73802. /**
  73803. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73804. */
  73805. this.upAxisSpace = BABYLON.Space.LOCAL;
  73806. /**
  73807. * Used to make an adjustment to the yaw of the bone.
  73808. */
  73809. this.adjustYaw = 0;
  73810. /**
  73811. * Used to make an adjustment to the pitch of the bone.
  73812. */
  73813. this.adjustPitch = 0;
  73814. /**
  73815. * Used to make an adjustment to the roll of the bone.
  73816. */
  73817. this.adjustRoll = 0;
  73818. /**
  73819. * 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).
  73820. */
  73821. this.slerpAmount = 1;
  73822. this._boneQuat = BABYLON.Quaternion.Identity();
  73823. this._slerping = false;
  73824. this._firstFrameSkipped = false;
  73825. this._fowardAxis = BABYLON.Vector3.Forward();
  73826. this.mesh = mesh;
  73827. this.bone = bone;
  73828. this.target = target;
  73829. if (options) {
  73830. if (options.adjustYaw) {
  73831. this.adjustYaw = options.adjustYaw;
  73832. }
  73833. if (options.adjustPitch) {
  73834. this.adjustPitch = options.adjustPitch;
  73835. }
  73836. if (options.adjustRoll) {
  73837. this.adjustRoll = options.adjustRoll;
  73838. }
  73839. if (options.maxYaw != null) {
  73840. this.maxYaw = options.maxYaw;
  73841. }
  73842. else {
  73843. this.maxYaw = Math.PI;
  73844. }
  73845. if (options.minYaw != null) {
  73846. this.minYaw = options.minYaw;
  73847. }
  73848. else {
  73849. this.minYaw = -Math.PI;
  73850. }
  73851. if (options.maxPitch != null) {
  73852. this.maxPitch = options.maxPitch;
  73853. }
  73854. else {
  73855. this.maxPitch = Math.PI;
  73856. }
  73857. if (options.minPitch != null) {
  73858. this.minPitch = options.minPitch;
  73859. }
  73860. else {
  73861. this.minPitch = -Math.PI;
  73862. }
  73863. if (options.slerpAmount != null) {
  73864. this.slerpAmount = options.slerpAmount;
  73865. }
  73866. if (options.upAxis != null) {
  73867. this.upAxis = options.upAxis;
  73868. }
  73869. if (options.upAxisSpace != null) {
  73870. this.upAxisSpace = options.upAxisSpace;
  73871. }
  73872. if (options.yawAxis != null || options.pitchAxis != null) {
  73873. var newYawAxis = BABYLON.Axis.Y;
  73874. var newPitchAxis = BABYLON.Axis.X;
  73875. if (options.yawAxis != null) {
  73876. newYawAxis = options.yawAxis.clone();
  73877. newYawAxis.normalize();
  73878. }
  73879. if (options.pitchAxis != null) {
  73880. newPitchAxis = options.pitchAxis.clone();
  73881. newPitchAxis.normalize();
  73882. }
  73883. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73884. this._transformYawPitch = BABYLON.Matrix.Identity();
  73885. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73886. this._transformYawPitchInv = this._transformYawPitch.clone();
  73887. this._transformYawPitch.invert();
  73888. }
  73889. }
  73890. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73891. this.upAxisSpace = BABYLON.Space.LOCAL;
  73892. }
  73893. }
  73894. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73895. /**
  73896. * Get/set the minimum yaw angle that the bone can look to.
  73897. */
  73898. get: function () {
  73899. return this._minYaw;
  73900. },
  73901. set: function (value) {
  73902. this._minYaw = value;
  73903. this._minYawSin = Math.sin(value);
  73904. this._minYawCos = Math.cos(value);
  73905. if (this._maxYaw != null) {
  73906. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73907. this._yawRange = this._maxYaw - this._minYaw;
  73908. }
  73909. },
  73910. enumerable: true,
  73911. configurable: true
  73912. });
  73913. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73914. /**
  73915. * Get/set the maximum yaw angle that the bone can look to.
  73916. */
  73917. get: function () {
  73918. return this._maxYaw;
  73919. },
  73920. set: function (value) {
  73921. this._maxYaw = value;
  73922. this._maxYawSin = Math.sin(value);
  73923. this._maxYawCos = Math.cos(value);
  73924. if (this._minYaw != null) {
  73925. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73926. this._yawRange = this._maxYaw - this._minYaw;
  73927. }
  73928. },
  73929. enumerable: true,
  73930. configurable: true
  73931. });
  73932. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73933. /**
  73934. * Get/set the minimum pitch angle that the bone can look to.
  73935. */
  73936. get: function () {
  73937. return this._minPitch;
  73938. },
  73939. set: function (value) {
  73940. this._minPitch = value;
  73941. this._minPitchTan = Math.tan(value);
  73942. },
  73943. enumerable: true,
  73944. configurable: true
  73945. });
  73946. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73947. /**
  73948. * Get/set the maximum pitch angle that the bone can look to.
  73949. */
  73950. get: function () {
  73951. return this._maxPitch;
  73952. },
  73953. set: function (value) {
  73954. this._maxPitch = value;
  73955. this._maxPitchTan = Math.tan(value);
  73956. },
  73957. enumerable: true,
  73958. configurable: true
  73959. });
  73960. /**
  73961. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73962. */
  73963. BoneLookController.prototype.update = function () {
  73964. //skip the first frame when slerping so that the mesh rotation is correct
  73965. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73966. this._firstFrameSkipped = true;
  73967. return;
  73968. }
  73969. var bone = this.bone;
  73970. var bonePos = BoneLookController._tmpVecs[0];
  73971. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73972. var target = this.target;
  73973. var _tmpMat1 = BoneLookController._tmpMats[0];
  73974. var _tmpMat2 = BoneLookController._tmpMats[1];
  73975. var mesh = this.mesh;
  73976. var parentBone = bone.getParent();
  73977. var upAxis = BoneLookController._tmpVecs[1];
  73978. upAxis.copyFrom(this.upAxis);
  73979. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73980. if (this._transformYawPitch) {
  73981. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73982. }
  73983. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73984. }
  73985. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73986. mesh.getDirectionToRef(upAxis, upAxis);
  73987. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73988. upAxis.normalize();
  73989. }
  73990. }
  73991. var checkYaw = false;
  73992. var checkPitch = false;
  73993. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73994. checkYaw = true;
  73995. }
  73996. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73997. checkPitch = true;
  73998. }
  73999. if (checkYaw || checkPitch) {
  74000. var spaceMat = BoneLookController._tmpMats[2];
  74001. var spaceMatInv = BoneLookController._tmpMats[3];
  74002. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  74003. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  74004. }
  74005. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  74006. spaceMat.copyFrom(mesh.getWorldMatrix());
  74007. }
  74008. else {
  74009. var forwardAxis = BoneLookController._tmpVecs[2];
  74010. forwardAxis.copyFrom(this._fowardAxis);
  74011. if (this._transformYawPitch) {
  74012. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  74013. }
  74014. if (parentBone) {
  74015. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  74016. }
  74017. else {
  74018. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  74019. }
  74020. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  74021. rightAxis.normalize();
  74022. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  74023. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  74024. }
  74025. spaceMat.invertToRef(spaceMatInv);
  74026. var xzlen = null;
  74027. if (checkPitch) {
  74028. var localTarget = BoneLookController._tmpVecs[3];
  74029. target.subtractToRef(bonePos, localTarget);
  74030. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74031. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74032. var pitch = Math.atan2(localTarget.y, xzlen);
  74033. var newPitch = pitch;
  74034. if (pitch > this._maxPitch) {
  74035. localTarget.y = this._maxPitchTan * xzlen;
  74036. newPitch = this._maxPitch;
  74037. }
  74038. else if (pitch < this._minPitch) {
  74039. localTarget.y = this._minPitchTan * xzlen;
  74040. newPitch = this._minPitch;
  74041. }
  74042. if (pitch != newPitch) {
  74043. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74044. localTarget.addInPlace(bonePos);
  74045. target = localTarget;
  74046. }
  74047. }
  74048. if (checkYaw) {
  74049. var localTarget = BoneLookController._tmpVecs[4];
  74050. target.subtractToRef(bonePos, localTarget);
  74051. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  74052. var yaw = Math.atan2(localTarget.x, localTarget.z);
  74053. var newYaw = yaw;
  74054. if (yaw > this._maxYaw || yaw < this._minYaw) {
  74055. if (xzlen == null) {
  74056. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74057. }
  74058. if (this._yawRange > Math.PI) {
  74059. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  74060. localTarget.z = this._maxYawCos * xzlen;
  74061. localTarget.x = this._maxYawSin * xzlen;
  74062. newYaw = this._maxYaw;
  74063. }
  74064. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  74065. localTarget.z = this._minYawCos * xzlen;
  74066. localTarget.x = this._minYawSin * xzlen;
  74067. newYaw = this._minYaw;
  74068. }
  74069. }
  74070. else {
  74071. if (yaw > this._maxYaw) {
  74072. localTarget.z = this._maxYawCos * xzlen;
  74073. localTarget.x = this._maxYawSin * xzlen;
  74074. newYaw = this._maxYaw;
  74075. }
  74076. else if (yaw < this._minYaw) {
  74077. localTarget.z = this._minYawCos * xzlen;
  74078. localTarget.x = this._minYawSin * xzlen;
  74079. newYaw = this._minYaw;
  74080. }
  74081. }
  74082. }
  74083. if (this._slerping && this._yawRange > Math.PI) {
  74084. //are we going to be crossing into the min/max region?
  74085. var boneFwd = BoneLookController._tmpVecs[8];
  74086. boneFwd.copyFrom(BABYLON.Axis.Z);
  74087. if (this._transformYawPitch) {
  74088. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  74089. }
  74090. var boneRotMat = BoneLookController._tmpMats[4];
  74091. this._boneQuat.toRotationMatrix(boneRotMat);
  74092. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  74093. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  74094. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  74095. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  74096. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  74097. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  74098. if (angBtwTar > angBtwMidYaw) {
  74099. if (xzlen == null) {
  74100. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  74101. }
  74102. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  74103. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  74104. if (angBtwMin < angBtwMax) {
  74105. newYaw = boneYaw + Math.PI * .75;
  74106. localTarget.z = Math.cos(newYaw) * xzlen;
  74107. localTarget.x = Math.sin(newYaw) * xzlen;
  74108. }
  74109. else {
  74110. newYaw = boneYaw - Math.PI * .75;
  74111. localTarget.z = Math.cos(newYaw) * xzlen;
  74112. localTarget.x = Math.sin(newYaw) * xzlen;
  74113. }
  74114. }
  74115. }
  74116. if (yaw != newYaw) {
  74117. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  74118. localTarget.addInPlace(bonePos);
  74119. target = localTarget;
  74120. }
  74121. }
  74122. }
  74123. var zaxis = BoneLookController._tmpVecs[5];
  74124. var xaxis = BoneLookController._tmpVecs[6];
  74125. var yaxis = BoneLookController._tmpVecs[7];
  74126. var _tmpQuat = BoneLookController._tmpQuat;
  74127. target.subtractToRef(bonePos, zaxis);
  74128. zaxis.normalize();
  74129. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  74130. xaxis.normalize();
  74131. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  74132. yaxis.normalize();
  74133. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  74134. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  74135. return;
  74136. }
  74137. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  74138. return;
  74139. }
  74140. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  74141. return;
  74142. }
  74143. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  74144. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  74145. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  74146. }
  74147. if (this.slerpAmount < 1) {
  74148. if (!this._slerping) {
  74149. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  74150. }
  74151. if (this._transformYawPitch) {
  74152. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74153. }
  74154. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  74155. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  74156. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  74157. this._slerping = true;
  74158. }
  74159. else {
  74160. if (this._transformYawPitch) {
  74161. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  74162. }
  74163. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  74164. this._slerping = false;
  74165. }
  74166. };
  74167. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  74168. var angDiff = ang2 - ang1;
  74169. angDiff %= Math.PI * 2;
  74170. if (angDiff > Math.PI) {
  74171. angDiff -= Math.PI * 2;
  74172. }
  74173. else if (angDiff < -Math.PI) {
  74174. angDiff += Math.PI * 2;
  74175. }
  74176. return angDiff;
  74177. };
  74178. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  74179. ang1 %= (2 * Math.PI);
  74180. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74181. ang2 %= (2 * Math.PI);
  74182. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74183. var ab = 0;
  74184. if (ang1 < ang2) {
  74185. ab = ang2 - ang1;
  74186. }
  74187. else {
  74188. ab = ang1 - ang2;
  74189. }
  74190. if (ab > Math.PI) {
  74191. ab = Math.PI * 2 - ab;
  74192. }
  74193. return ab;
  74194. };
  74195. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  74196. ang %= (2 * Math.PI);
  74197. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  74198. ang1 %= (2 * Math.PI);
  74199. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  74200. ang2 %= (2 * Math.PI);
  74201. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  74202. if (ang1 < ang2) {
  74203. if (ang > ang1 && ang < ang2) {
  74204. return true;
  74205. }
  74206. }
  74207. else {
  74208. if (ang > ang2 && ang < ang1) {
  74209. return true;
  74210. }
  74211. }
  74212. return false;
  74213. };
  74214. 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()];
  74215. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  74216. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  74217. return BoneLookController;
  74218. }());
  74219. BABYLON.BoneLookController = BoneLookController;
  74220. })(BABYLON || (BABYLON = {}));
  74221. //# sourceMappingURL=babylon.boneLookController.js.map
  74222. "use strict";
  74223. var BABYLON;
  74224. (function (BABYLON) {
  74225. var Skeleton = /** @class */ (function () {
  74226. function Skeleton(name, id, scene) {
  74227. this.name = name;
  74228. this.id = id;
  74229. this.bones = new Array();
  74230. this.needInitialSkinMatrix = false;
  74231. this._isDirty = true;
  74232. this._meshesWithPoseMatrix = new Array();
  74233. this._identity = BABYLON.Matrix.Identity();
  74234. this._ranges = {};
  74235. this._lastAbsoluteTransformsUpdateId = -1;
  74236. /**
  74237. * Specifies if the skeleton should be serialized.
  74238. */
  74239. this.doNotSerialize = false;
  74240. // Events
  74241. /**
  74242. * An event triggered before computing the skeleton's matrices
  74243. * @type {BABYLON.Observable}
  74244. */
  74245. this.onBeforeComputeObservable = new BABYLON.Observable();
  74246. this.bones = [];
  74247. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74248. scene.skeletons.push(this);
  74249. //make sure it will recalculate the matrix next time prepare is called.
  74250. this._isDirty = true;
  74251. }
  74252. // Members
  74253. Skeleton.prototype.getTransformMatrices = function (mesh) {
  74254. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  74255. return mesh._bonesTransformMatrices;
  74256. }
  74257. if (!this._transformMatrices) {
  74258. this.prepare();
  74259. }
  74260. return this._transformMatrices;
  74261. };
  74262. Skeleton.prototype.getScene = function () {
  74263. return this._scene;
  74264. };
  74265. // Methods
  74266. /**
  74267. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  74268. */
  74269. Skeleton.prototype.toString = function (fullDetails) {
  74270. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  74271. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  74272. if (fullDetails) {
  74273. ret += ", Ranges: {";
  74274. var first = true;
  74275. for (var name_1 in this._ranges) {
  74276. if (first) {
  74277. ret += ", ";
  74278. first = false;
  74279. }
  74280. ret += name_1;
  74281. }
  74282. ret += "}";
  74283. }
  74284. return ret;
  74285. };
  74286. /**
  74287. * Get bone's index searching by name
  74288. * @param {string} name is bone's name to search for
  74289. * @return {number} Indice of the bone. Returns -1 if not found
  74290. */
  74291. Skeleton.prototype.getBoneIndexByName = function (name) {
  74292. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  74293. if (this.bones[boneIndex].name === name) {
  74294. return boneIndex;
  74295. }
  74296. }
  74297. return -1;
  74298. };
  74299. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  74300. // check name not already in use
  74301. if (!this._ranges[name]) {
  74302. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  74303. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74304. if (this.bones[i].animations[0]) {
  74305. this.bones[i].animations[0].createRange(name, from, to);
  74306. }
  74307. }
  74308. }
  74309. };
  74310. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  74311. if (deleteFrames === void 0) { deleteFrames = true; }
  74312. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74313. if (this.bones[i].animations[0]) {
  74314. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  74315. }
  74316. }
  74317. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  74318. };
  74319. Skeleton.prototype.getAnimationRange = function (name) {
  74320. return this._ranges[name];
  74321. };
  74322. /**
  74323. * Returns as an Array, all AnimationRanges defined on this skeleton
  74324. */
  74325. Skeleton.prototype.getAnimationRanges = function () {
  74326. var animationRanges = [];
  74327. var name;
  74328. var i = 0;
  74329. for (name in this._ranges) {
  74330. animationRanges[i] = this._ranges[name];
  74331. i++;
  74332. }
  74333. return animationRanges;
  74334. };
  74335. /**
  74336. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  74337. */
  74338. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  74339. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  74340. if (this._ranges[name] || !source.getAnimationRange(name)) {
  74341. return false;
  74342. }
  74343. var ret = true;
  74344. var frameOffset = this._getHighestAnimationFrame() + 1;
  74345. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  74346. var boneDict = {};
  74347. var sourceBones = source.bones;
  74348. var nBones;
  74349. var i;
  74350. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  74351. boneDict[sourceBones[i].name] = sourceBones[i];
  74352. }
  74353. if (this.bones.length !== sourceBones.length) {
  74354. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  74355. ret = false;
  74356. }
  74357. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  74358. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  74359. var boneName = this.bones[i].name;
  74360. var sourceBone = boneDict[boneName];
  74361. if (sourceBone) {
  74362. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  74363. }
  74364. else {
  74365. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  74366. ret = false;
  74367. }
  74368. }
  74369. // do not call createAnimationRange(), since it also is done to bones, which was already done
  74370. var range = source.getAnimationRange(name);
  74371. if (range) {
  74372. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  74373. }
  74374. return ret;
  74375. };
  74376. Skeleton.prototype.returnToRest = function () {
  74377. for (var index = 0; index < this.bones.length; index++) {
  74378. this.bones[index].returnToRest();
  74379. }
  74380. };
  74381. Skeleton.prototype._getHighestAnimationFrame = function () {
  74382. var ret = 0;
  74383. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  74384. if (this.bones[i].animations[0]) {
  74385. var highest = this.bones[i].animations[0].getHighestFrame();
  74386. if (ret < highest) {
  74387. ret = highest;
  74388. }
  74389. }
  74390. }
  74391. return ret;
  74392. };
  74393. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  74394. var range = this.getAnimationRange(name);
  74395. if (!range) {
  74396. return null;
  74397. }
  74398. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  74399. };
  74400. Skeleton.prototype._markAsDirty = function () {
  74401. this._isDirty = true;
  74402. };
  74403. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  74404. this._meshesWithPoseMatrix.push(mesh);
  74405. };
  74406. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  74407. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  74408. if (index > -1) {
  74409. this._meshesWithPoseMatrix.splice(index, 1);
  74410. }
  74411. };
  74412. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  74413. this.onBeforeComputeObservable.notifyObservers(this);
  74414. for (var index = 0; index < this.bones.length; index++) {
  74415. var bone = this.bones[index];
  74416. var parentBone = bone.getParent();
  74417. if (parentBone) {
  74418. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  74419. }
  74420. else {
  74421. if (initialSkinMatrix) {
  74422. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  74423. }
  74424. else {
  74425. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  74426. }
  74427. }
  74428. if (bone._index !== -1) {
  74429. var mappedIndex = bone._index === null ? index : bone._index;
  74430. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  74431. }
  74432. }
  74433. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  74434. };
  74435. Skeleton.prototype.prepare = function () {
  74436. if (!this._isDirty) {
  74437. return;
  74438. }
  74439. if (this.needInitialSkinMatrix) {
  74440. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  74441. var mesh = this._meshesWithPoseMatrix[index];
  74442. var poseMatrix = mesh.getPoseMatrix();
  74443. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  74444. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74445. }
  74446. if (this._synchronizedWithMesh !== mesh) {
  74447. this._synchronizedWithMesh = mesh;
  74448. // Prepare bones
  74449. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  74450. var bone = this.bones[boneIndex];
  74451. if (!bone.getParent()) {
  74452. var matrix = bone.getBaseMatrix();
  74453. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  74454. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  74455. }
  74456. }
  74457. }
  74458. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  74459. }
  74460. }
  74461. else {
  74462. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  74463. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  74464. }
  74465. this._computeTransformMatrices(this._transformMatrices, null);
  74466. }
  74467. this._isDirty = false;
  74468. this._scene._activeBones.addCount(this.bones.length, false);
  74469. };
  74470. Skeleton.prototype.getAnimatables = function () {
  74471. if (!this._animatables || this._animatables.length !== this.bones.length) {
  74472. this._animatables = [];
  74473. for (var index = 0; index < this.bones.length; index++) {
  74474. this._animatables.push(this.bones[index]);
  74475. }
  74476. }
  74477. return this._animatables;
  74478. };
  74479. Skeleton.prototype.clone = function (name, id) {
  74480. var result = new Skeleton(name, id || name, this._scene);
  74481. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74482. for (var index = 0; index < this.bones.length; index++) {
  74483. var source = this.bones[index];
  74484. var parentBone = null;
  74485. var parent_1 = source.getParent();
  74486. if (parent_1) {
  74487. var parentIndex = this.bones.indexOf(parent_1);
  74488. parentBone = result.bones[parentIndex];
  74489. }
  74490. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  74491. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  74492. }
  74493. if (this._ranges) {
  74494. result._ranges = {};
  74495. for (var rangeName in this._ranges) {
  74496. var range = this._ranges[rangeName];
  74497. if (range) {
  74498. result._ranges[rangeName] = range.clone();
  74499. }
  74500. }
  74501. }
  74502. this._isDirty = true;
  74503. return result;
  74504. };
  74505. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  74506. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  74507. this.bones.forEach(function (bone) {
  74508. bone.animations.forEach(function (animation) {
  74509. animation.enableBlending = true;
  74510. animation.blendingSpeed = blendingSpeed;
  74511. });
  74512. });
  74513. };
  74514. Skeleton.prototype.dispose = function () {
  74515. this._meshesWithPoseMatrix = [];
  74516. // Animations
  74517. this.getScene().stopAnimation(this);
  74518. // Remove from scene
  74519. this.getScene().removeSkeleton(this);
  74520. };
  74521. Skeleton.prototype.serialize = function () {
  74522. var serializationObject = {};
  74523. serializationObject.name = this.name;
  74524. serializationObject.id = this.id;
  74525. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  74526. serializationObject.bones = [];
  74527. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  74528. for (var index = 0; index < this.bones.length; index++) {
  74529. var bone = this.bones[index];
  74530. var parent_2 = bone.getParent();
  74531. var serializedBone = {
  74532. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74533. name: bone.name,
  74534. matrix: bone.getBaseMatrix().toArray(),
  74535. rest: bone.getRestPose().toArray()
  74536. };
  74537. serializationObject.bones.push(serializedBone);
  74538. if (bone.length) {
  74539. serializedBone.length = bone.length;
  74540. }
  74541. if (bone.animations && bone.animations.length > 0) {
  74542. serializedBone.animation = bone.animations[0].serialize();
  74543. }
  74544. serializationObject.ranges = [];
  74545. for (var name in this._ranges) {
  74546. var source = this._ranges[name];
  74547. if (!source) {
  74548. continue;
  74549. }
  74550. var range = {};
  74551. range.name = name;
  74552. range.from = source.from;
  74553. range.to = source.to;
  74554. serializationObject.ranges.push(range);
  74555. }
  74556. }
  74557. return serializationObject;
  74558. };
  74559. Skeleton.Parse = function (parsedSkeleton, scene) {
  74560. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74561. if (parsedSkeleton.dimensionsAtRest) {
  74562. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74563. }
  74564. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74565. var index;
  74566. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74567. var parsedBone = parsedSkeleton.bones[index];
  74568. var parentBone = null;
  74569. if (parsedBone.parentBoneIndex > -1) {
  74570. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74571. }
  74572. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74573. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74574. if (parsedBone.length) {
  74575. bone.length = parsedBone.length;
  74576. }
  74577. if (parsedBone.animation) {
  74578. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74579. }
  74580. }
  74581. // placed after bones, so createAnimationRange can cascade down
  74582. if (parsedSkeleton.ranges) {
  74583. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74584. var data = parsedSkeleton.ranges[index];
  74585. skeleton.createAnimationRange(data.name, data.from, data.to);
  74586. }
  74587. }
  74588. return skeleton;
  74589. };
  74590. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74591. if (forceUpdate === void 0) { forceUpdate = false; }
  74592. var renderId = this._scene.getRenderId();
  74593. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74594. this.bones[0].computeAbsoluteTransforms();
  74595. this._lastAbsoluteTransformsUpdateId = renderId;
  74596. }
  74597. };
  74598. Skeleton.prototype.getPoseMatrix = function () {
  74599. var poseMatrix = null;
  74600. if (this._meshesWithPoseMatrix.length > 0) {
  74601. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74602. }
  74603. return poseMatrix;
  74604. };
  74605. Skeleton.prototype.sortBones = function () {
  74606. var bones = new Array();
  74607. var visited = new Array(this.bones.length);
  74608. for (var index = 0; index < this.bones.length; index++) {
  74609. this._sortBones(index, bones, visited);
  74610. }
  74611. this.bones = bones;
  74612. };
  74613. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74614. if (visited[index]) {
  74615. return;
  74616. }
  74617. visited[index] = true;
  74618. var bone = this.bones[index];
  74619. if (bone._index === undefined) {
  74620. bone._index = index;
  74621. }
  74622. var parentBone = bone.getParent();
  74623. if (parentBone) {
  74624. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74625. }
  74626. bones.push(bone);
  74627. };
  74628. return Skeleton;
  74629. }());
  74630. BABYLON.Skeleton = Skeleton;
  74631. })(BABYLON || (BABYLON = {}));
  74632. //# sourceMappingURL=babylon.skeleton.js.map
  74633. "use strict";
  74634. var BABYLON;
  74635. (function (BABYLON) {
  74636. var SphericalPolynomial = /** @class */ (function () {
  74637. function SphericalPolynomial() {
  74638. this.x = BABYLON.Vector3.Zero();
  74639. this.y = BABYLON.Vector3.Zero();
  74640. this.z = BABYLON.Vector3.Zero();
  74641. this.xx = BABYLON.Vector3.Zero();
  74642. this.yy = BABYLON.Vector3.Zero();
  74643. this.zz = BABYLON.Vector3.Zero();
  74644. this.xy = BABYLON.Vector3.Zero();
  74645. this.yz = BABYLON.Vector3.Zero();
  74646. this.zx = BABYLON.Vector3.Zero();
  74647. }
  74648. SphericalPolynomial.prototype.addAmbient = function (color) {
  74649. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74650. this.xx = this.xx.add(colorVector);
  74651. this.yy = this.yy.add(colorVector);
  74652. this.zz = this.zz.add(colorVector);
  74653. };
  74654. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74655. var result = new SphericalPolynomial();
  74656. result.x = harmonics.L11.scale(1.02333);
  74657. result.y = harmonics.L1_1.scale(1.02333);
  74658. result.z = harmonics.L10.scale(1.02333);
  74659. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74660. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74661. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74662. result.yz = harmonics.L2_1.scale(0.858086);
  74663. result.zx = harmonics.L21.scale(0.858086);
  74664. result.xy = harmonics.L2_2.scale(0.858086);
  74665. result.scale(1.0 / Math.PI);
  74666. return result;
  74667. };
  74668. SphericalPolynomial.prototype.scale = function (scale) {
  74669. this.x = this.x.scale(scale);
  74670. this.y = this.y.scale(scale);
  74671. this.z = this.z.scale(scale);
  74672. this.xx = this.xx.scale(scale);
  74673. this.yy = this.yy.scale(scale);
  74674. this.zz = this.zz.scale(scale);
  74675. this.yz = this.yz.scale(scale);
  74676. this.zx = this.zx.scale(scale);
  74677. this.xy = this.xy.scale(scale);
  74678. };
  74679. return SphericalPolynomial;
  74680. }());
  74681. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74682. var SphericalHarmonics = /** @class */ (function () {
  74683. function SphericalHarmonics() {
  74684. this.L00 = BABYLON.Vector3.Zero();
  74685. this.L1_1 = BABYLON.Vector3.Zero();
  74686. this.L10 = BABYLON.Vector3.Zero();
  74687. this.L11 = BABYLON.Vector3.Zero();
  74688. this.L2_2 = BABYLON.Vector3.Zero();
  74689. this.L2_1 = BABYLON.Vector3.Zero();
  74690. this.L20 = BABYLON.Vector3.Zero();
  74691. this.L21 = BABYLON.Vector3.Zero();
  74692. this.L22 = BABYLON.Vector3.Zero();
  74693. }
  74694. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74695. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74696. var c = colorVector.scale(deltaSolidAngle);
  74697. this.L00 = this.L00.add(c.scale(0.282095));
  74698. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74699. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74700. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74701. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74702. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74703. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74704. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74705. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74706. };
  74707. SphericalHarmonics.prototype.scale = function (scale) {
  74708. this.L00 = this.L00.scale(scale);
  74709. this.L1_1 = this.L1_1.scale(scale);
  74710. this.L10 = this.L10.scale(scale);
  74711. this.L11 = this.L11.scale(scale);
  74712. this.L2_2 = this.L2_2.scale(scale);
  74713. this.L2_1 = this.L2_1.scale(scale);
  74714. this.L20 = this.L20.scale(scale);
  74715. this.L21 = this.L21.scale(scale);
  74716. this.L22 = this.L22.scale(scale);
  74717. };
  74718. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74719. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74720. //
  74721. // E_lm = A_l * L_lm
  74722. //
  74723. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74724. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74725. // the scaling factors are given in equation 9.
  74726. // Constant (Band 0)
  74727. this.L00 = this.L00.scale(3.141593);
  74728. // Linear (Band 1)
  74729. this.L1_1 = this.L1_1.scale(2.094395);
  74730. this.L10 = this.L10.scale(2.094395);
  74731. this.L11 = this.L11.scale(2.094395);
  74732. // Quadratic (Band 2)
  74733. this.L2_2 = this.L2_2.scale(0.785398);
  74734. this.L2_1 = this.L2_1.scale(0.785398);
  74735. this.L20 = this.L20.scale(0.785398);
  74736. this.L21 = this.L21.scale(0.785398);
  74737. this.L22 = this.L22.scale(0.785398);
  74738. };
  74739. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74740. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74741. // L = (1/pi) * E * rho
  74742. //
  74743. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74744. this.scale(1.0 / Math.PI);
  74745. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74746. // (The pixel shader must apply albedo after texture fetches, etc).
  74747. };
  74748. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74749. var result = new SphericalHarmonics();
  74750. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74751. result.L1_1 = polynomial.y.scale(0.977204);
  74752. result.L10 = polynomial.z.scale(0.977204);
  74753. result.L11 = polynomial.x.scale(0.977204);
  74754. result.L2_2 = polynomial.xy.scale(1.16538);
  74755. result.L2_1 = polynomial.yz.scale(1.16538);
  74756. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74757. result.L21 = polynomial.zx.scale(1.16538);
  74758. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74759. result.scale(Math.PI);
  74760. return result;
  74761. };
  74762. return SphericalHarmonics;
  74763. }());
  74764. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74765. })(BABYLON || (BABYLON = {}));
  74766. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74767. "use strict";
  74768. var BABYLON;
  74769. (function (BABYLON) {
  74770. var FileFaceOrientation = /** @class */ (function () {
  74771. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74772. this.name = name;
  74773. this.worldAxisForNormal = worldAxisForNormal;
  74774. this.worldAxisForFileX = worldAxisForFileX;
  74775. this.worldAxisForFileY = worldAxisForFileY;
  74776. }
  74777. return FileFaceOrientation;
  74778. }());
  74779. ;
  74780. /**
  74781. * Helper class dealing with the extraction of spherical polynomial dataArray
  74782. * from a cube map.
  74783. */
  74784. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74785. function CubeMapToSphericalPolynomialTools() {
  74786. }
  74787. /**
  74788. * Converts a texture to the according Spherical Polynomial data.
  74789. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74790. *
  74791. * @param texture The texture to extract the information from.
  74792. * @return The Spherical Polynomial data.
  74793. */
  74794. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74795. if (!texture.isCube) {
  74796. // Only supports cube Textures currently.
  74797. return null;
  74798. }
  74799. var size = texture.getSize().width;
  74800. var right = texture.readPixels(0);
  74801. var left = texture.readPixels(1);
  74802. var up;
  74803. var down;
  74804. if (texture.isRenderTarget) {
  74805. up = texture.readPixels(3);
  74806. down = texture.readPixels(2);
  74807. }
  74808. else {
  74809. up = texture.readPixels(2);
  74810. down = texture.readPixels(3);
  74811. }
  74812. var front = texture.readPixels(4);
  74813. var back = texture.readPixels(5);
  74814. var gammaSpace = texture.gammaSpace;
  74815. // Always read as RGBA.
  74816. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74817. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74818. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74819. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74820. }
  74821. var cubeInfo = {
  74822. size: size,
  74823. right: right,
  74824. left: left,
  74825. up: up,
  74826. down: down,
  74827. front: front,
  74828. back: back,
  74829. format: format,
  74830. type: type,
  74831. gammaSpace: gammaSpace,
  74832. };
  74833. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74834. };
  74835. /**
  74836. * Converts a cubemap to the according Spherical Polynomial data.
  74837. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74838. *
  74839. * @param cubeInfo The Cube map to extract the information from.
  74840. * @return The Spherical Polynomial data.
  74841. */
  74842. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74843. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74844. var totalSolidAngle = 0.0;
  74845. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74846. var du = 2.0 / cubeInfo.size;
  74847. var dv = du;
  74848. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74849. var minUV = du * 0.5 - 1.0;
  74850. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74851. var fileFace = this.FileFaces[faceIndex];
  74852. var dataArray = cubeInfo[fileFace.name];
  74853. var v = minUV;
  74854. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74855. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74856. // Because SP is still linear, so summation is fine in that basis.
  74857. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74858. for (var y = 0; y < cubeInfo.size; y++) {
  74859. var u = minUV;
  74860. for (var x = 0; x < cubeInfo.size; x++) {
  74861. // World direction (not normalised)
  74862. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74863. worldDirection.normalize();
  74864. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74865. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74866. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74867. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74868. // Handle Integer types.
  74869. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74870. r /= 255;
  74871. g /= 255;
  74872. b /= 255;
  74873. }
  74874. // Handle Gamma space textures.
  74875. if (cubeInfo.gammaSpace) {
  74876. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74877. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74878. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74879. }
  74880. var color = new BABYLON.Color3(r, g, b);
  74881. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74882. totalSolidAngle += deltaSolidAngle;
  74883. u += du;
  74884. }
  74885. v += dv;
  74886. }
  74887. }
  74888. // Solid angle for entire sphere is 4*pi
  74889. var sphereSolidAngle = 4.0 * Math.PI;
  74890. // Adjust the solid angle to allow for how many faces we processed.
  74891. var facesProcessed = 6.0;
  74892. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74893. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74894. // This is needed because the numerical integration over the cube uses a
  74895. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74896. // and also to compensate for accumulative error due to float precision in the summation.
  74897. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74898. sphericalHarmonics.scale(correctionFactor);
  74899. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74900. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74901. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74902. };
  74903. CubeMapToSphericalPolynomialTools.FileFaces = [
  74904. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74905. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74906. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74907. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74908. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74909. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74910. ];
  74911. return CubeMapToSphericalPolynomialTools;
  74912. }());
  74913. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74914. })(BABYLON || (BABYLON = {}));
  74915. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74916. "use strict";
  74917. var BABYLON;
  74918. (function (BABYLON) {
  74919. /**
  74920. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74921. */
  74922. var PanoramaToCubeMapTools = /** @class */ (function () {
  74923. function PanoramaToCubeMapTools() {
  74924. }
  74925. /**
  74926. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74927. *
  74928. * @param float32Array The source data.
  74929. * @param inputWidth The width of the input panorama.
  74930. * @param inputhHeight The height of the input panorama.
  74931. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74932. * @return The cubemap data
  74933. */
  74934. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74935. if (!float32Array) {
  74936. throw "ConvertPanoramaToCubemap: input cannot be null";
  74937. }
  74938. if (float32Array.length != inputWidth * inputHeight * 3) {
  74939. throw "ConvertPanoramaToCubemap: input size is wrong";
  74940. }
  74941. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74942. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74943. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74944. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74945. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74946. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74947. return {
  74948. front: textureFront,
  74949. back: textureBack,
  74950. left: textureLeft,
  74951. right: textureRight,
  74952. up: textureUp,
  74953. down: textureDown,
  74954. size: size,
  74955. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74956. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74957. gammaSpace: false,
  74958. };
  74959. };
  74960. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74961. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74962. var textureArray = new Float32Array(buffer);
  74963. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74964. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74965. var dy = 1 / texSize;
  74966. var fy = 0;
  74967. for (var y = 0; y < texSize; y++) {
  74968. var xv1 = faceData[0];
  74969. var xv2 = faceData[2];
  74970. for (var x = 0; x < texSize; x++) {
  74971. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74972. v.normalize();
  74973. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74974. // 3 channels per pixels
  74975. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74976. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74977. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74978. xv1 = xv1.add(rotDX1);
  74979. xv2 = xv2.add(rotDX2);
  74980. }
  74981. fy += dy;
  74982. }
  74983. return textureArray;
  74984. };
  74985. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74986. var theta = Math.atan2(vDir.z, vDir.x);
  74987. var phi = Math.acos(vDir.y);
  74988. while (theta < -Math.PI)
  74989. theta += 2 * Math.PI;
  74990. while (theta > Math.PI)
  74991. theta -= 2 * Math.PI;
  74992. var dx = theta / Math.PI;
  74993. var dy = phi / Math.PI;
  74994. // recenter.
  74995. dx = dx * 0.5 + 0.5;
  74996. var px = Math.round(dx * inputWidth);
  74997. if (px < 0)
  74998. px = 0;
  74999. else if (px >= inputWidth)
  75000. px = inputWidth - 1;
  75001. var py = Math.round(dy * inputHeight);
  75002. if (py < 0)
  75003. py = 0;
  75004. else if (py >= inputHeight)
  75005. py = inputHeight - 1;
  75006. var inputY = (inputHeight - py - 1);
  75007. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  75008. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  75009. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  75010. return {
  75011. r: r,
  75012. g: g,
  75013. b: b
  75014. };
  75015. };
  75016. PanoramaToCubeMapTools.FACE_FRONT = [
  75017. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75018. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75019. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75020. new BABYLON.Vector3(1.0, 1.0, -1.0)
  75021. ];
  75022. PanoramaToCubeMapTools.FACE_BACK = [
  75023. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75024. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75025. new BABYLON.Vector3(1.0, 1.0, 1.0),
  75026. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  75027. ];
  75028. PanoramaToCubeMapTools.FACE_RIGHT = [
  75029. new BABYLON.Vector3(1.0, -1.0, -1.0),
  75030. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75031. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75032. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75033. ];
  75034. PanoramaToCubeMapTools.FACE_LEFT = [
  75035. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75036. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75037. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75038. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  75039. ];
  75040. PanoramaToCubeMapTools.FACE_DOWN = [
  75041. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  75042. new BABYLON.Vector3(1.0, 1.0, -1.0),
  75043. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  75044. new BABYLON.Vector3(1.0, 1.0, 1.0)
  75045. ];
  75046. PanoramaToCubeMapTools.FACE_UP = [
  75047. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  75048. new BABYLON.Vector3(1.0, -1.0, 1.0),
  75049. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  75050. new BABYLON.Vector3(1.0, -1.0, -1.0)
  75051. ];
  75052. return PanoramaToCubeMapTools;
  75053. }());
  75054. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  75055. })(BABYLON || (BABYLON = {}));
  75056. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  75057. "use strict";
  75058. var BABYLON;
  75059. (function (BABYLON) {
  75060. ;
  75061. /**
  75062. * This groups tools to convert HDR texture to native colors array.
  75063. */
  75064. var HDRTools = /** @class */ (function () {
  75065. function HDRTools() {
  75066. }
  75067. HDRTools.Ldexp = function (mantissa, exponent) {
  75068. if (exponent > 1023) {
  75069. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  75070. }
  75071. if (exponent < -1074) {
  75072. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  75073. }
  75074. return mantissa * Math.pow(2, exponent);
  75075. };
  75076. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  75077. if (exponent > 0) {
  75078. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  75079. float32array[index + 0] = red * exponent;
  75080. float32array[index + 1] = green * exponent;
  75081. float32array[index + 2] = blue * exponent;
  75082. }
  75083. else {
  75084. float32array[index + 0] = 0;
  75085. float32array[index + 1] = 0;
  75086. float32array[index + 2] = 0;
  75087. }
  75088. };
  75089. HDRTools.readStringLine = function (uint8array, startIndex) {
  75090. var line = "";
  75091. var character = "";
  75092. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  75093. character = String.fromCharCode(uint8array[i]);
  75094. if (character == "\n") {
  75095. break;
  75096. }
  75097. line += character;
  75098. }
  75099. return line;
  75100. };
  75101. /**
  75102. * Reads header information from an RGBE texture stored in a native array.
  75103. * More information on this format are available here:
  75104. * https://en.wikipedia.org/wiki/RGBE_image_format
  75105. *
  75106. * @param uint8array The binary file stored in native array.
  75107. * @return The header information.
  75108. */
  75109. HDRTools.RGBE_ReadHeader = function (uint8array) {
  75110. var height = 0;
  75111. var width = 0;
  75112. var line = this.readStringLine(uint8array, 0);
  75113. if (line[0] != '#' || line[1] != '?') {
  75114. throw "Bad HDR Format.";
  75115. }
  75116. var endOfHeader = false;
  75117. var findFormat = false;
  75118. var lineIndex = 0;
  75119. do {
  75120. lineIndex += (line.length + 1);
  75121. line = this.readStringLine(uint8array, lineIndex);
  75122. if (line == "FORMAT=32-bit_rle_rgbe") {
  75123. findFormat = true;
  75124. }
  75125. else if (line.length == 0) {
  75126. endOfHeader = true;
  75127. }
  75128. } while (!endOfHeader);
  75129. if (!findFormat) {
  75130. throw "HDR Bad header format, unsupported FORMAT";
  75131. }
  75132. lineIndex += (line.length + 1);
  75133. line = this.readStringLine(uint8array, lineIndex);
  75134. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  75135. var match = sizeRegexp.exec(line);
  75136. // TODO. Support +Y and -X if needed.
  75137. if (!match || match.length < 3) {
  75138. throw "HDR Bad header format, no size";
  75139. }
  75140. width = parseInt(match[2]);
  75141. height = parseInt(match[1]);
  75142. if (width < 8 || width > 0x7fff) {
  75143. throw "HDR Bad header format, unsupported size";
  75144. }
  75145. lineIndex += (line.length + 1);
  75146. return {
  75147. height: height,
  75148. width: width,
  75149. dataPosition: lineIndex
  75150. };
  75151. };
  75152. /**
  75153. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  75154. * This RGBE texture needs to store the information as a panorama.
  75155. *
  75156. * More information on this format are available here:
  75157. * https://en.wikipedia.org/wiki/RGBE_image_format
  75158. *
  75159. * @param buffer The binary file stored in an array buffer.
  75160. * @param size The expected size of the extracted cubemap.
  75161. * @return The Cube Map information.
  75162. */
  75163. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  75164. var uint8array = new Uint8Array(buffer);
  75165. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  75166. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75167. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  75168. return cubeMapData;
  75169. };
  75170. /**
  75171. * Returns the pixels data extracted from an RGBE texture.
  75172. * This pixels will be stored left to right up to down in the R G B order in one array.
  75173. *
  75174. * More information on this format are available here:
  75175. * https://en.wikipedia.org/wiki/RGBE_image_format
  75176. *
  75177. * @param uint8array The binary file stored in an array buffer.
  75178. * @param hdrInfo The header information of the file.
  75179. * @return The pixels data in RGB right to left up to down order.
  75180. */
  75181. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  75182. // Keep for multi format supports.
  75183. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  75184. };
  75185. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  75186. var num_scanlines = hdrInfo.height;
  75187. var scanline_width = hdrInfo.width;
  75188. var a, b, c, d, count;
  75189. var dataIndex = hdrInfo.dataPosition;
  75190. var index = 0, endIndex = 0, i = 0;
  75191. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  75192. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  75193. // 3 channels of 4 bytes per pixel in float.
  75194. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  75195. var resultArray = new Float32Array(resultBuffer);
  75196. // read in each successive scanline
  75197. while (num_scanlines > 0) {
  75198. a = uint8array[dataIndex++];
  75199. b = uint8array[dataIndex++];
  75200. c = uint8array[dataIndex++];
  75201. d = uint8array[dataIndex++];
  75202. if (a != 2 || b != 2 || (c & 0x80)) {
  75203. // this file is not run length encoded
  75204. throw "HDR Bad header format, not RLE";
  75205. }
  75206. if (((c << 8) | d) != scanline_width) {
  75207. throw "HDR Bad header format, wrong scan line width";
  75208. }
  75209. index = 0;
  75210. // read each of the four channels for the scanline into the buffer
  75211. for (i = 0; i < 4; i++) {
  75212. endIndex = (i + 1) * scanline_width;
  75213. while (index < endIndex) {
  75214. a = uint8array[dataIndex++];
  75215. b = uint8array[dataIndex++];
  75216. if (a > 128) {
  75217. // a run of the same value
  75218. count = a - 128;
  75219. if ((count == 0) || (count > endIndex - index)) {
  75220. throw "HDR Bad Format, bad scanline data (run)";
  75221. }
  75222. while (count-- > 0) {
  75223. scanLineArray[index++] = b;
  75224. }
  75225. }
  75226. else {
  75227. // a non-run
  75228. count = a;
  75229. if ((count == 0) || (count > endIndex - index)) {
  75230. throw "HDR Bad Format, bad scanline data (non-run)";
  75231. }
  75232. scanLineArray[index++] = b;
  75233. if (--count > 0) {
  75234. for (var j = 0; j < count; j++) {
  75235. scanLineArray[index++] = uint8array[dataIndex++];
  75236. }
  75237. }
  75238. }
  75239. }
  75240. }
  75241. // now convert data from buffer into floats
  75242. for (i = 0; i < scanline_width; i++) {
  75243. a = scanLineArray[i];
  75244. b = scanLineArray[i + scanline_width];
  75245. c = scanLineArray[i + 2 * scanline_width];
  75246. d = scanLineArray[i + 3 * scanline_width];
  75247. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  75248. }
  75249. num_scanlines--;
  75250. }
  75251. return resultArray;
  75252. };
  75253. return HDRTools;
  75254. }());
  75255. BABYLON.HDRTools = HDRTools;
  75256. })(BABYLON || (BABYLON = {}));
  75257. //# sourceMappingURL=babylon.hdr.js.map
  75258. "use strict";
  75259. var BABYLON;
  75260. (function (BABYLON) {
  75261. /**
  75262. * This represents a texture coming from an HDR input.
  75263. *
  75264. * The only supported format is currently panorama picture stored in RGBE format.
  75265. * Example of such files can be found on HDRLib: http://hdrlib.com/
  75266. */
  75267. var HDRCubeTexture = /** @class */ (function (_super) {
  75268. __extends(HDRCubeTexture, _super);
  75269. /**
  75270. * Instantiates an HDRTexture from the following parameters.
  75271. *
  75272. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  75273. * @param scene The scene the texture will be used in
  75274. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  75275. * @param noMipmap Forces to not generate the mipmap if true
  75276. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  75277. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  75278. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  75279. */
  75280. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  75281. if (noMipmap === void 0) { noMipmap = false; }
  75282. if (generateHarmonics === void 0) { generateHarmonics = true; }
  75283. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  75284. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  75285. if (onLoad === void 0) { onLoad = null; }
  75286. if (onError === void 0) { onError = null; }
  75287. var _this = _super.call(this, scene) || this;
  75288. _this._useInGammaSpace = false;
  75289. _this._generateHarmonics = true;
  75290. _this._isBABYLONPreprocessed = false;
  75291. _this._onLoad = null;
  75292. _this._onError = null;
  75293. /**
  75294. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  75295. */
  75296. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  75297. /**
  75298. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  75299. * This is usefull at run time to apply the good shader.
  75300. */
  75301. _this.isPMREM = false;
  75302. _this._isBlocking = true;
  75303. /**
  75304. * Gets or sets the center of the bounding box associated with the cube texture
  75305. * It must define where the camera used to render the texture was set
  75306. */
  75307. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  75308. if (!url) {
  75309. return _this;
  75310. }
  75311. _this.name = url;
  75312. _this.url = url;
  75313. _this.hasAlpha = false;
  75314. _this.isCube = true;
  75315. _this._textureMatrix = BABYLON.Matrix.Identity();
  75316. _this._onLoad = onLoad;
  75317. _this._onError = onError;
  75318. _this.gammaSpace = false;
  75319. var caps = scene.getEngine().getCaps();
  75320. if (size) {
  75321. _this._isBABYLONPreprocessed = false;
  75322. _this._noMipmap = noMipmap;
  75323. _this._size = size;
  75324. _this._useInGammaSpace = useInGammaSpace;
  75325. _this._usePMREMGenerator = usePMREMGenerator &&
  75326. caps.textureLOD &&
  75327. caps.textureFloat &&
  75328. !_this._useInGammaSpace;
  75329. }
  75330. else {
  75331. _this._isBABYLONPreprocessed = true;
  75332. _this._noMipmap = false;
  75333. _this._useInGammaSpace = false;
  75334. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  75335. !_this._useInGammaSpace;
  75336. }
  75337. _this.isPMREM = _this._usePMREMGenerator;
  75338. _this._texture = _this._getFromCache(url, _this._noMipmap);
  75339. if (!_this._texture) {
  75340. if (!scene.useDelayedTextureLoading) {
  75341. _this.loadTexture();
  75342. }
  75343. else {
  75344. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  75345. }
  75346. }
  75347. return _this;
  75348. }
  75349. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  75350. /**
  75351. * Gets wether or not the texture is blocking during loading.
  75352. */
  75353. get: function () {
  75354. return this._isBlocking;
  75355. },
  75356. /**
  75357. * Sets wether or not the texture is blocking during loading.
  75358. */
  75359. set: function (value) {
  75360. this._isBlocking = value;
  75361. },
  75362. enumerable: true,
  75363. configurable: true
  75364. });
  75365. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  75366. get: function () {
  75367. return this._boundingBoxSize;
  75368. },
  75369. /**
  75370. * Gets or sets the size of the bounding box associated with the cube texture
  75371. * When defined, the cubemap will switch to local mode
  75372. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  75373. * @example https://www.babylonjs-playground.com/#RNASML
  75374. */
  75375. set: function (value) {
  75376. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  75377. return;
  75378. }
  75379. this._boundingBoxSize = value;
  75380. var scene = this.getScene();
  75381. if (scene) {
  75382. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  75383. }
  75384. },
  75385. enumerable: true,
  75386. configurable: true
  75387. });
  75388. /**
  75389. * Occurs when the file is a preprocessed .babylon.hdr file.
  75390. */
  75391. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  75392. var _this = this;
  75393. var mipLevels = 0;
  75394. var floatArrayView = null;
  75395. var scene = this.getScene();
  75396. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  75397. var mips = new Array();
  75398. if (!floatArrayView) {
  75399. return mips;
  75400. }
  75401. var startIndex = 30;
  75402. for (var level = 0; level < mipLevels; level++) {
  75403. mips.push([]);
  75404. // Fill each pixel of the mip level.
  75405. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  75406. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75407. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  75408. mips[level].push(faceData);
  75409. startIndex += faceSize;
  75410. }
  75411. }
  75412. return mips;
  75413. } : null;
  75414. var callback = function (buffer) {
  75415. var scene = _this.getScene();
  75416. if (!scene) {
  75417. return null;
  75418. }
  75419. // Create Native Array Views
  75420. var intArrayView = new Int32Array(buffer);
  75421. floatArrayView = new Float32Array(buffer);
  75422. // Fill header.
  75423. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  75424. _this._size = intArrayView[1]; // CubeMap max mip face size.
  75425. // Update Texture Information.
  75426. if (!_this._texture) {
  75427. return null;
  75428. }
  75429. _this._texture.updateSize(_this._size, _this._size);
  75430. // Fill polynomial information.
  75431. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  75432. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  75433. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  75434. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  75435. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  75436. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  75437. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  75438. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  75439. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  75440. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  75441. _this.sphericalPolynomial = sphericalPolynomial;
  75442. // Fill pixel data.
  75443. mipLevels = intArrayView[29]; // Number of mip levels.
  75444. var startIndex = 30;
  75445. var data = [];
  75446. var faceSize = Math.pow(_this._size, 2) * 3;
  75447. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  75448. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  75449. startIndex += faceSize;
  75450. }
  75451. var results = [];
  75452. var byteArray = null;
  75453. // Push each faces.
  75454. for (var k = 0; k < 6; k++) {
  75455. var dataFace = null;
  75456. // To be deprecated.
  75457. if (version === 1) {
  75458. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  75459. dataFace = data[j];
  75460. }
  75461. // If special cases.
  75462. if (!mipmapGenerator && dataFace) {
  75463. if (!scene.getEngine().getCaps().textureFloat) {
  75464. // 3 channels of 1 bytes per pixel in bytes.
  75465. var byteBuffer = new ArrayBuffer(faceSize);
  75466. byteArray = new Uint8Array(byteBuffer);
  75467. }
  75468. for (var i = 0; i < _this._size * _this._size; i++) {
  75469. // Put in gamma space if requested.
  75470. if (_this._useInGammaSpace) {
  75471. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75472. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75473. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75474. }
  75475. // Convert to int texture for fallback.
  75476. if (byteArray) {
  75477. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75478. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75479. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75480. // May use luminance instead if the result is not accurate.
  75481. var max = Math.max(Math.max(r, g), b);
  75482. if (max > 255) {
  75483. var scale = 255 / max;
  75484. r *= scale;
  75485. g *= scale;
  75486. b *= scale;
  75487. }
  75488. byteArray[(i * 3) + 0] = r;
  75489. byteArray[(i * 3) + 1] = g;
  75490. byteArray[(i * 3) + 2] = b;
  75491. }
  75492. }
  75493. }
  75494. // Fill the array accordingly.
  75495. if (byteArray) {
  75496. results.push(byteArray);
  75497. }
  75498. else {
  75499. results.push(dataFace);
  75500. }
  75501. }
  75502. return results;
  75503. };
  75504. if (scene) {
  75505. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  75506. }
  75507. };
  75508. /**
  75509. * Occurs when the file is raw .hdr file.
  75510. */
  75511. HDRCubeTexture.prototype.loadHDRTexture = function () {
  75512. var _this = this;
  75513. var callback = function (buffer) {
  75514. var scene = _this.getScene();
  75515. if (!scene) {
  75516. return null;
  75517. }
  75518. // Extract the raw linear data.
  75519. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  75520. // Generate harmonics if needed.
  75521. if (_this._generateHarmonics) {
  75522. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  75523. _this.sphericalPolynomial = sphericalPolynomial;
  75524. }
  75525. var results = [];
  75526. var byteArray = null;
  75527. // Push each faces.
  75528. for (var j = 0; j < 6; j++) {
  75529. // Create uintarray fallback.
  75530. if (!scene.getEngine().getCaps().textureFloat) {
  75531. // 3 channels of 1 bytes per pixel in bytes.
  75532. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75533. byteArray = new Uint8Array(byteBuffer);
  75534. }
  75535. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75536. // If special cases.
  75537. if (_this._useInGammaSpace || byteArray) {
  75538. for (var i = 0; i < _this._size * _this._size; i++) {
  75539. // Put in gamma space if requested.
  75540. if (_this._useInGammaSpace) {
  75541. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75542. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75543. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75544. }
  75545. // Convert to int texture for fallback.
  75546. if (byteArray) {
  75547. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75548. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75549. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75550. // May use luminance instead if the result is not accurate.
  75551. var max = Math.max(Math.max(r, g), b);
  75552. if (max > 255) {
  75553. var scale = 255 / max;
  75554. r *= scale;
  75555. g *= scale;
  75556. b *= scale;
  75557. }
  75558. byteArray[(i * 3) + 0] = r;
  75559. byteArray[(i * 3) + 1] = g;
  75560. byteArray[(i * 3) + 2] = b;
  75561. }
  75562. }
  75563. }
  75564. if (byteArray) {
  75565. results.push(byteArray);
  75566. }
  75567. else {
  75568. results.push(dataFace);
  75569. }
  75570. }
  75571. return results;
  75572. };
  75573. var mipmapGenerator = null;
  75574. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75575. // if (!this._noMipmap &&
  75576. // this._usePMREMGenerator) {
  75577. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75578. // // Custom setup of the generator matching with the PBR shader values.
  75579. // var generator = new BABYLON.PMREMGenerator(data,
  75580. // this._size,
  75581. // this._size,
  75582. // 0,
  75583. // 3,
  75584. // this.getScene().getEngine().getCaps().textureFloat,
  75585. // 2048,
  75586. // 0.25,
  75587. // false,
  75588. // true);
  75589. // return generator.filterCubeMap();
  75590. // };
  75591. // }
  75592. var scene = this.getScene();
  75593. if (scene) {
  75594. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  75595. }
  75596. };
  75597. /**
  75598. * Starts the loading process of the texture.
  75599. */
  75600. HDRCubeTexture.prototype.loadTexture = function () {
  75601. if (this._isBABYLONPreprocessed) {
  75602. this.loadBabylonTexture();
  75603. }
  75604. else {
  75605. this.loadHDRTexture();
  75606. }
  75607. };
  75608. HDRCubeTexture.prototype.clone = function () {
  75609. var scene = this.getScene();
  75610. if (!scene) {
  75611. return this;
  75612. }
  75613. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75614. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75615. // Base texture
  75616. newTexture.level = this.level;
  75617. newTexture.wrapU = this.wrapU;
  75618. newTexture.wrapV = this.wrapV;
  75619. newTexture.coordinatesIndex = this.coordinatesIndex;
  75620. newTexture.coordinatesMode = this.coordinatesMode;
  75621. return newTexture;
  75622. };
  75623. // Methods
  75624. HDRCubeTexture.prototype.delayLoad = function () {
  75625. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75626. return;
  75627. }
  75628. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75629. this._texture = this._getFromCache(this.url, this._noMipmap);
  75630. if (!this._texture) {
  75631. this.loadTexture();
  75632. }
  75633. };
  75634. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75635. return this._textureMatrix;
  75636. };
  75637. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75638. this._textureMatrix = value;
  75639. };
  75640. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75641. var texture = null;
  75642. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75643. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75644. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75645. texture.name = parsedTexture.name;
  75646. texture.hasAlpha = parsedTexture.hasAlpha;
  75647. texture.level = parsedTexture.level;
  75648. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75649. texture.isBlocking = parsedTexture.isBlocking;
  75650. }
  75651. if (texture) {
  75652. if (parsedTexture.boundingBoxPosition) {
  75653. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75654. }
  75655. if (parsedTexture.boundingBoxSize) {
  75656. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75657. }
  75658. }
  75659. return texture;
  75660. };
  75661. HDRCubeTexture.prototype.serialize = function () {
  75662. if (!this.name) {
  75663. return null;
  75664. }
  75665. var serializationObject = {};
  75666. serializationObject.name = this.name;
  75667. serializationObject.hasAlpha = this.hasAlpha;
  75668. serializationObject.isCube = true;
  75669. serializationObject.level = this.level;
  75670. serializationObject.size = this._size;
  75671. serializationObject.coordinatesMode = this.coordinatesMode;
  75672. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75673. serializationObject.generateHarmonics = this._generateHarmonics;
  75674. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75675. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75676. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75677. serializationObject.noMipmap = this._noMipmap;
  75678. serializationObject.isBlocking = this._isBlocking;
  75679. return serializationObject;
  75680. };
  75681. /**
  75682. * Saves as a file the data contained in the texture in a binary format.
  75683. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75684. * as the spherical used in the lighting.
  75685. * @param url The HDR file url.
  75686. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75687. * @param onError Method called if any error happens during download.
  75688. * @return The packed binary data.
  75689. */
  75690. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75691. if (onError === void 0) { onError = null; }
  75692. var callback = function (buffer) {
  75693. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75694. // Returns a URL you can use as a href.
  75695. var objUrl = window.URL.createObjectURL(data);
  75696. // Simulates a link to it and click to dowload.
  75697. var a = document.createElement("a");
  75698. document.body.appendChild(a);
  75699. a.style.display = "none";
  75700. a.href = objUrl;
  75701. a.download = "envmap.babylon.hdr";
  75702. a.click();
  75703. };
  75704. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75705. };
  75706. /**
  75707. * Serializes the data contained in the texture in a binary format.
  75708. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75709. * as the spherical used in the lighting.
  75710. * @param url The HDR file url.
  75711. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75712. * @param onError Method called if any error happens during download.
  75713. * @return The packed binary data.
  75714. */
  75715. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75716. if (onError === void 0) { onError = null; }
  75717. // Needs the url tho create the texture.
  75718. if (!url) {
  75719. return;
  75720. }
  75721. // Check Power of two size.
  75722. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75723. return;
  75724. }
  75725. // Coming Back in 3.x.
  75726. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75727. };
  75728. HDRCubeTexture._facesMapping = [
  75729. "right",
  75730. "left",
  75731. "up",
  75732. "down",
  75733. "front",
  75734. "back"
  75735. ];
  75736. return HDRCubeTexture;
  75737. }(BABYLON.BaseTexture));
  75738. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75739. })(BABYLON || (BABYLON = {}));
  75740. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75741. "use strict";
  75742. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75743. // Huge respect for a such great lib.
  75744. // Earcut license:
  75745. // Copyright (c) 2016, Mapbox
  75746. //
  75747. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75748. // with or without fee is hereby granted, provided that the above copyright notice
  75749. // and this permission notice appear in all copies.
  75750. //
  75751. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75752. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75753. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75754. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75755. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75756. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75757. // THIS SOFTWARE.
  75758. var Earcut;
  75759. (function (Earcut) {
  75760. /**
  75761. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75762. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75763. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75764. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75765. */
  75766. function earcut(data, holeIndices, dim) {
  75767. dim = dim || 2;
  75768. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75769. if (!outerNode)
  75770. return triangles;
  75771. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75772. if (hasHoles)
  75773. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75774. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75775. if (data.length > 80 * dim) {
  75776. minX = maxX = data[0];
  75777. minY = maxY = data[1];
  75778. for (var i = dim; i < outerLen; i += dim) {
  75779. x = data[i];
  75780. y = data[i + 1];
  75781. if (x < minX)
  75782. minX = x;
  75783. if (y < minY)
  75784. minY = y;
  75785. if (x > maxX)
  75786. maxX = x;
  75787. if (y > maxY)
  75788. maxY = y;
  75789. }
  75790. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75791. size = Math.max(maxX - minX, maxY - minY);
  75792. }
  75793. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75794. return triangles;
  75795. }
  75796. Earcut.earcut = earcut;
  75797. var Node = /** @class */ (function () {
  75798. function Node(i, x, y) {
  75799. this.i = i;
  75800. this.x = x;
  75801. this.y = y;
  75802. this.prev = null;
  75803. this.next = null;
  75804. this.z = null;
  75805. this.prevZ = null;
  75806. this.nextZ = null;
  75807. this.steiner = false;
  75808. }
  75809. return Node;
  75810. }());
  75811. // create a circular doubly linked list from polygon points in the specified winding order
  75812. function linkedList(data, start, end, dim, clockwise) {
  75813. var i, last = null;
  75814. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75815. for (i = start; i < end; i += dim)
  75816. last = insertNode(i, data[i], data[i + 1], last);
  75817. }
  75818. else {
  75819. for (i = end - dim; i >= start; i -= dim)
  75820. last = insertNode(i, data[i], data[i + 1], last);
  75821. }
  75822. if (last && equals(last, last.next)) {
  75823. removeNode(last);
  75824. last = last.next;
  75825. }
  75826. return last;
  75827. }
  75828. // eliminate colinear or duplicate points
  75829. function filterPoints(start, end) {
  75830. if (!start)
  75831. return start;
  75832. if (!end)
  75833. end = start;
  75834. var p = start, again;
  75835. do {
  75836. again = false;
  75837. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75838. removeNode(p);
  75839. p = end = p.prev;
  75840. if (p === p.next)
  75841. return undefined;
  75842. again = true;
  75843. }
  75844. else {
  75845. p = p.next;
  75846. }
  75847. } while (again || p !== end);
  75848. return end;
  75849. }
  75850. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75851. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75852. if (!ear)
  75853. return;
  75854. // interlink polygon nodes in z-order
  75855. if (!pass && size)
  75856. indexCurve(ear, minX, minY, size);
  75857. var stop = ear, prev, next;
  75858. // iterate through ears, slicing them one by one
  75859. while (ear.prev !== ear.next) {
  75860. prev = ear.prev;
  75861. next = ear.next;
  75862. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75863. // cut off the triangle
  75864. triangles.push(prev.i / dim);
  75865. triangles.push(ear.i / dim);
  75866. triangles.push(next.i / dim);
  75867. removeNode(ear);
  75868. // skipping the next vertice leads to less sliver triangles
  75869. ear = next.next;
  75870. stop = next.next;
  75871. continue;
  75872. }
  75873. ear = next;
  75874. // if we looped through the whole remaining polygon and can't find any more ears
  75875. if (ear === stop) {
  75876. // try filtering points and slicing again
  75877. if (!pass) {
  75878. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75879. // if this didn't work, try curing all small self-intersections locally
  75880. }
  75881. else if (pass === 1) {
  75882. ear = cureLocalIntersections(ear, triangles, dim);
  75883. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75884. // as a last resort, try splitting the remaining polygon into two
  75885. }
  75886. else if (pass === 2) {
  75887. splitEarcut(ear, triangles, dim, minX, minY, size);
  75888. }
  75889. break;
  75890. }
  75891. }
  75892. }
  75893. // check whether a polygon node forms a valid ear with adjacent nodes
  75894. function isEar(ear) {
  75895. var a = ear.prev, b = ear, c = ear.next;
  75896. if (area(a, b, c) >= 0)
  75897. return false; // reflex, can't be an ear
  75898. // now make sure we don't have other points inside the potential ear
  75899. var p = ear.next.next;
  75900. while (p !== ear.prev) {
  75901. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75902. area(p.prev, p, p.next) >= 0)
  75903. return false;
  75904. p = p.next;
  75905. }
  75906. return true;
  75907. }
  75908. function isEarHashed(ear, minX, minY, size) {
  75909. var a = ear.prev, b = ear, c = ear.next;
  75910. if (area(a, b, c) >= 0)
  75911. return false; // reflex, can't be an ear
  75912. // triangle bbox; min & max are calculated like this for speed
  75913. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75914. // z-order range for the current triangle bbox;
  75915. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75916. // first look for points inside the triangle in increasing z-order
  75917. var p = ear.nextZ;
  75918. while (p && p.z <= maxZ) {
  75919. if (p !== ear.prev &&
  75920. p !== ear.next &&
  75921. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75922. area(p.prev, p, p.next) >= 0)
  75923. return false;
  75924. p = p.nextZ;
  75925. }
  75926. // then look for points in decreasing z-order
  75927. p = ear.prevZ;
  75928. while (p && p.z >= minZ) {
  75929. if (p !== ear.prev &&
  75930. p !== ear.next &&
  75931. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75932. area(p.prev, p, p.next) >= 0)
  75933. return false;
  75934. p = p.prevZ;
  75935. }
  75936. return true;
  75937. }
  75938. // go through all polygon nodes and cure small local self-intersections
  75939. function cureLocalIntersections(start, triangles, dim) {
  75940. var p = start;
  75941. do {
  75942. var a = p.prev, b = p.next.next;
  75943. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75944. triangles.push(a.i / dim);
  75945. triangles.push(p.i / dim);
  75946. triangles.push(b.i / dim);
  75947. // remove two nodes involved
  75948. removeNode(p);
  75949. removeNode(p.next);
  75950. p = start = b;
  75951. }
  75952. p = p.next;
  75953. } while (p !== start);
  75954. return p;
  75955. }
  75956. // try splitting polygon into two and triangulate them independently
  75957. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75958. // look for a valid diagonal that divides the polygon into two
  75959. var a = start;
  75960. do {
  75961. var b = a.next.next;
  75962. while (b !== a.prev) {
  75963. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75964. // split the polygon in two by the diagonal
  75965. var c = splitPolygon(a, b);
  75966. // filter colinear points around the cuts
  75967. a = filterPoints(a, a.next);
  75968. c = filterPoints(c, c.next);
  75969. // run earcut on each half
  75970. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75971. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75972. return;
  75973. }
  75974. b = b.next;
  75975. }
  75976. a = a.next;
  75977. } while (a !== start);
  75978. }
  75979. // link every hole into the outer loop, producing a single-ring polygon without holes
  75980. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75981. var queue = [], i, len, start, end, list;
  75982. for (i = 0, len = holeIndices.length; i < len; i++) {
  75983. start = holeIndices[i] * dim;
  75984. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75985. list = linkedList(data, start, end, dim, false);
  75986. if (list === list.next)
  75987. list.steiner = true;
  75988. queue.push(getLeftmost(list));
  75989. }
  75990. queue.sort(compareX);
  75991. // process holes from left to right
  75992. for (i = 0; i < queue.length; i++) {
  75993. eliminateHole(queue[i], outerNode);
  75994. outerNode = filterPoints(outerNode, outerNode.next);
  75995. }
  75996. return outerNode;
  75997. }
  75998. function compareX(a, b) {
  75999. return a.x - b.x;
  76000. }
  76001. // find a bridge between vertices that connects hole with an outer ring and and link it
  76002. function eliminateHole(hole, outerNode) {
  76003. outerNode = findHoleBridge(hole, outerNode);
  76004. if (outerNode) {
  76005. var b = splitPolygon(outerNode, hole);
  76006. filterPoints(b, b.next);
  76007. }
  76008. }
  76009. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  76010. function findHoleBridge(hole, outerNode) {
  76011. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  76012. // find a segment intersected by a ray from the hole's leftmost point to the left;
  76013. // segment's endpoint with lesser x will be potential connection point
  76014. do {
  76015. if (hy <= p.y && hy >= p.next.y) {
  76016. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  76017. if (x <= hx && x > qx) {
  76018. qx = x;
  76019. if (x === hx) {
  76020. if (hy === p.y)
  76021. return p;
  76022. if (hy === p.next.y)
  76023. return p.next;
  76024. }
  76025. m = p.x < p.next.x ? p : p.next;
  76026. }
  76027. }
  76028. p = p.next;
  76029. } while (p !== outerNode);
  76030. if (!m)
  76031. return null;
  76032. if (hx === qx)
  76033. return m.prev; // hole touches outer segment; pick lower endpoint
  76034. // look for points inside the triangle of hole point, segment intersection and endpoint;
  76035. // if there are no points found, we have a valid connection;
  76036. // otherwise choose the point of the minimum angle with the ray as connection point
  76037. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  76038. p = m.next;
  76039. while (p !== stop) {
  76040. if (hx >= p.x &&
  76041. p.x >= mx &&
  76042. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  76043. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  76044. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  76045. m = p;
  76046. tanMin = tan;
  76047. }
  76048. }
  76049. p = p.next;
  76050. }
  76051. return m;
  76052. }
  76053. // interlink polygon nodes in z-order
  76054. function indexCurve(start, minX, minY, size) {
  76055. var p = start;
  76056. do {
  76057. if (p.z === null)
  76058. p.z = zOrder(p.x, p.y, minX, minY, size);
  76059. p.prevZ = p.prev;
  76060. p.nextZ = p.next;
  76061. p = p.next;
  76062. } while (p !== start);
  76063. p.prevZ.nextZ = null;
  76064. p.prevZ = null;
  76065. sortLinked(p);
  76066. }
  76067. // Simon Tatham's linked list merge sort algorithm
  76068. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  76069. function sortLinked(list) {
  76070. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  76071. do {
  76072. p = list;
  76073. list = null;
  76074. tail = null;
  76075. numMerges = 0;
  76076. while (p) {
  76077. numMerges++;
  76078. q = p;
  76079. pSize = 0;
  76080. for (i = 0; i < inSize; i++) {
  76081. pSize++;
  76082. q = q.nextZ;
  76083. if (!q)
  76084. break;
  76085. }
  76086. qSize = inSize;
  76087. while (pSize > 0 || (qSize > 0 && q)) {
  76088. if (pSize === 0) {
  76089. e = q;
  76090. q = q.nextZ;
  76091. qSize--;
  76092. }
  76093. else if (qSize === 0 || !q) {
  76094. e = p;
  76095. p = p.nextZ;
  76096. pSize--;
  76097. }
  76098. else if (p.z <= q.z) {
  76099. e = p;
  76100. p = p.nextZ;
  76101. pSize--;
  76102. }
  76103. else {
  76104. e = q;
  76105. q = q.nextZ;
  76106. qSize--;
  76107. }
  76108. if (tail)
  76109. tail.nextZ = e;
  76110. else
  76111. list = e;
  76112. e.prevZ = tail;
  76113. tail = e;
  76114. }
  76115. p = q;
  76116. }
  76117. tail.nextZ = null;
  76118. inSize *= 2;
  76119. } while (numMerges > 1);
  76120. return list;
  76121. }
  76122. // z-order of a point given coords and size of the data bounding box
  76123. function zOrder(x, y, minX, minY, size) {
  76124. // coords are transformed into non-negative 15-bit integer range
  76125. x = 32767 * (x - minX) / size;
  76126. y = 32767 * (y - minY) / size;
  76127. x = (x | (x << 8)) & 0x00FF00FF;
  76128. x = (x | (x << 4)) & 0x0F0F0F0F;
  76129. x = (x | (x << 2)) & 0x33333333;
  76130. x = (x | (x << 1)) & 0x55555555;
  76131. y = (y | (y << 8)) & 0x00FF00FF;
  76132. y = (y | (y << 4)) & 0x0F0F0F0F;
  76133. y = (y | (y << 2)) & 0x33333333;
  76134. y = (y | (y << 1)) & 0x55555555;
  76135. return x | (y << 1);
  76136. }
  76137. // find the leftmost node of a polygon ring
  76138. function getLeftmost(start) {
  76139. var p = start, leftmost = start;
  76140. do {
  76141. if (p.x < leftmost.x)
  76142. leftmost = p;
  76143. p = p.next;
  76144. } while (p !== start);
  76145. return leftmost;
  76146. }
  76147. // check if a point lies within a convex triangle
  76148. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  76149. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  76150. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  76151. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  76152. }
  76153. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  76154. function isValidDiagonal(a, b) {
  76155. return a.next.i !== b.i &&
  76156. a.prev.i !== b.i &&
  76157. !intersectsPolygon(a, b) &&
  76158. locallyInside(a, b) &&
  76159. locallyInside(b, a) &&
  76160. middleInside(a, b);
  76161. }
  76162. // signed area of a triangle
  76163. function area(p, q, r) {
  76164. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  76165. }
  76166. // check if two points are equal
  76167. function equals(p1, p2) {
  76168. return p1.x === p2.x && p1.y === p2.y;
  76169. }
  76170. // check if two segments intersect
  76171. function intersects(p1, q1, p2, q2) {
  76172. if ((equals(p1, q1) && equals(p2, q2)) ||
  76173. (equals(p1, q2) && equals(p2, q1)))
  76174. return true;
  76175. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  76176. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  76177. }
  76178. // check if a polygon diagonal intersects any polygon segments
  76179. function intersectsPolygon(a, b) {
  76180. var p = a;
  76181. do {
  76182. if (p.i !== a.i &&
  76183. p.next.i !== a.i &&
  76184. p.i !== b.i &&
  76185. p.next.i !== b.i &&
  76186. intersects(p, p.next, a, b))
  76187. return true;
  76188. p = p.next;
  76189. } while (p !== a);
  76190. return false;
  76191. }
  76192. // check if a polygon diagonal is locally inside the polygon
  76193. function locallyInside(a, b) {
  76194. return area(a.prev, a, a.next) < 0
  76195. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  76196. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  76197. }
  76198. // check if the middle point of a polygon diagonal is inside the polygon
  76199. function middleInside(a, b) {
  76200. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  76201. do {
  76202. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  76203. inside = !inside;
  76204. p = p.next;
  76205. } while (p !== a);
  76206. return inside;
  76207. }
  76208. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  76209. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  76210. function splitPolygon(a, b) {
  76211. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  76212. a.next = b;
  76213. b.prev = a;
  76214. a2.next = an;
  76215. an.prev = a2;
  76216. b2.next = a2;
  76217. a2.prev = b2;
  76218. bp.next = b2;
  76219. b2.prev = bp;
  76220. return b2;
  76221. }
  76222. // create a node and optionally link it with previous one (in a circular doubly linked list)
  76223. function insertNode(i, x, y, last) {
  76224. var p = new Node(i, x, y);
  76225. if (!last) {
  76226. p.prev = p;
  76227. p.next = p;
  76228. }
  76229. else {
  76230. p.next = last.next;
  76231. p.prev = last;
  76232. last.next.prev = p;
  76233. last.next = p;
  76234. }
  76235. return p;
  76236. }
  76237. function removeNode(p) {
  76238. p.next.prev = p.prev;
  76239. p.prev.next = p.next;
  76240. if (p.prevZ)
  76241. p.prevZ.nextZ = p.nextZ;
  76242. if (p.nextZ)
  76243. p.nextZ.prevZ = p.prevZ;
  76244. }
  76245. /**
  76246. * return a percentage difference between the polygon area and its triangulation area;
  76247. * used to verify correctness of triangulation
  76248. */
  76249. function deviation(data, holeIndices, dim, triangles) {
  76250. var hasHoles = holeIndices && holeIndices.length;
  76251. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  76252. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  76253. if (hasHoles) {
  76254. for (var i = 0, len = holeIndices.length; i < len; i++) {
  76255. var start = holeIndices[i] * dim;
  76256. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  76257. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  76258. }
  76259. }
  76260. var trianglesArea = 0;
  76261. for (i = 0; i < triangles.length; i += 3) {
  76262. var a = triangles[i] * dim;
  76263. var b = triangles[i + 1] * dim;
  76264. var c = triangles[i + 2] * dim;
  76265. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  76266. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  76267. }
  76268. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  76269. }
  76270. Earcut.deviation = deviation;
  76271. ;
  76272. function signedArea(data, start, end, dim) {
  76273. var sum = 0;
  76274. for (var i = start, j = end - dim; i < end; i += dim) {
  76275. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  76276. j = i;
  76277. }
  76278. return sum;
  76279. }
  76280. /**
  76281. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  76282. */
  76283. function flatten(data) {
  76284. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  76285. for (var i = 0; i < data.length; i++) {
  76286. for (var j = 0; j < data[i].length; j++) {
  76287. for (var d = 0; d < dim; d++)
  76288. result.vertices.push(data[i][j][d]);
  76289. }
  76290. if (i > 0) {
  76291. holeIndex += data[i - 1].length;
  76292. result.holes.push(holeIndex);
  76293. }
  76294. }
  76295. return result;
  76296. }
  76297. Earcut.flatten = flatten;
  76298. ;
  76299. })(Earcut || (Earcut = {}));
  76300. //# sourceMappingURL=babylon.earcut.js.map
  76301. "use strict";
  76302. var BABYLON;
  76303. (function (BABYLON) {
  76304. var IndexedVector2 = /** @class */ (function (_super) {
  76305. __extends(IndexedVector2, _super);
  76306. function IndexedVector2(original, index) {
  76307. var _this = _super.call(this, original.x, original.y) || this;
  76308. _this.index = index;
  76309. return _this;
  76310. }
  76311. return IndexedVector2;
  76312. }(BABYLON.Vector2));
  76313. var PolygonPoints = /** @class */ (function () {
  76314. function PolygonPoints() {
  76315. this.elements = new Array();
  76316. }
  76317. PolygonPoints.prototype.add = function (originalPoints) {
  76318. var _this = this;
  76319. var result = new Array();
  76320. originalPoints.forEach(function (point) {
  76321. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  76322. var newPoint = new IndexedVector2(point, _this.elements.length);
  76323. result.push(newPoint);
  76324. _this.elements.push(newPoint);
  76325. }
  76326. });
  76327. return result;
  76328. };
  76329. PolygonPoints.prototype.computeBounds = function () {
  76330. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76331. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  76332. this.elements.forEach(function (point) {
  76333. // x
  76334. if (point.x < lmin.x) {
  76335. lmin.x = point.x;
  76336. }
  76337. else if (point.x > lmax.x) {
  76338. lmax.x = point.x;
  76339. }
  76340. // y
  76341. if (point.y < lmin.y) {
  76342. lmin.y = point.y;
  76343. }
  76344. else if (point.y > lmax.y) {
  76345. lmax.y = point.y;
  76346. }
  76347. });
  76348. return {
  76349. min: lmin,
  76350. max: lmax,
  76351. width: lmax.x - lmin.x,
  76352. height: lmax.y - lmin.y
  76353. };
  76354. };
  76355. return PolygonPoints;
  76356. }());
  76357. var Polygon = /** @class */ (function () {
  76358. function Polygon() {
  76359. }
  76360. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  76361. return [
  76362. new BABYLON.Vector2(xmin, ymin),
  76363. new BABYLON.Vector2(xmax, ymin),
  76364. new BABYLON.Vector2(xmax, ymax),
  76365. new BABYLON.Vector2(xmin, ymax)
  76366. ];
  76367. };
  76368. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  76369. if (cx === void 0) { cx = 0; }
  76370. if (cy === void 0) { cy = 0; }
  76371. if (numberOfSides === void 0) { numberOfSides = 32; }
  76372. var result = new Array();
  76373. var angle = 0;
  76374. var increment = (Math.PI * 2) / numberOfSides;
  76375. for (var i = 0; i < numberOfSides; i++) {
  76376. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  76377. angle -= increment;
  76378. }
  76379. return result;
  76380. };
  76381. Polygon.Parse = function (input) {
  76382. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  76383. var i, result = [];
  76384. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  76385. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  76386. }
  76387. return result;
  76388. };
  76389. Polygon.StartingAt = function (x, y) {
  76390. return BABYLON.Path2.StartingAt(x, y);
  76391. };
  76392. return Polygon;
  76393. }());
  76394. BABYLON.Polygon = Polygon;
  76395. var PolygonMeshBuilder = /** @class */ (function () {
  76396. function PolygonMeshBuilder(name, contours, scene) {
  76397. this._points = new PolygonPoints();
  76398. this._outlinepoints = new PolygonPoints();
  76399. this._holes = new Array();
  76400. this._epoints = new Array();
  76401. this._eholes = new Array();
  76402. this._name = name;
  76403. this._scene = scene;
  76404. var points;
  76405. if (contours instanceof BABYLON.Path2) {
  76406. points = contours.getPoints();
  76407. }
  76408. else {
  76409. points = contours;
  76410. }
  76411. this._addToepoint(points);
  76412. this._points.add(points);
  76413. this._outlinepoints.add(points);
  76414. }
  76415. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  76416. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  76417. var p = points_1[_i];
  76418. this._epoints.push(p.x, p.y);
  76419. }
  76420. };
  76421. PolygonMeshBuilder.prototype.addHole = function (hole) {
  76422. this._points.add(hole);
  76423. var holepoints = new PolygonPoints();
  76424. holepoints.add(hole);
  76425. this._holes.push(holepoints);
  76426. this._eholes.push(this._epoints.length / 2);
  76427. this._addToepoint(hole);
  76428. return this;
  76429. };
  76430. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  76431. var _this = this;
  76432. if (updatable === void 0) { updatable = false; }
  76433. if (depth === void 0) { depth = 0; }
  76434. var result = new BABYLON.Mesh(this._name, this._scene);
  76435. var normals = new Array();
  76436. var positions = new Array();
  76437. var uvs = new Array();
  76438. var bounds = this._points.computeBounds();
  76439. this._points.elements.forEach(function (p) {
  76440. normals.push(0, 1.0, 0);
  76441. positions.push(p.x, 0, p.y);
  76442. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  76443. });
  76444. var indices = new Array();
  76445. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  76446. for (var i = 0; i < res.length; i++) {
  76447. indices.push(res[i]);
  76448. }
  76449. if (depth > 0) {
  76450. var positionscount = (positions.length / 3); //get the current pointcount
  76451. this._points.elements.forEach(function (p) {
  76452. normals.push(0, -1.0, 0);
  76453. positions.push(p.x, -depth, p.y);
  76454. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  76455. });
  76456. var totalCount = indices.length;
  76457. for (var i = 0; i < totalCount; i += 3) {
  76458. var i0 = indices[i + 0];
  76459. var i1 = indices[i + 1];
  76460. var i2 = indices[i + 2];
  76461. indices.push(i2 + positionscount);
  76462. indices.push(i1 + positionscount);
  76463. indices.push(i0 + positionscount);
  76464. }
  76465. //Add the sides
  76466. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  76467. this._holes.forEach(function (hole) {
  76468. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  76469. });
  76470. }
  76471. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  76472. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  76473. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  76474. result.setIndices(indices);
  76475. return result;
  76476. };
  76477. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  76478. var StartIndex = positions.length / 3;
  76479. var ulength = 0;
  76480. for (var i = 0; i < points.elements.length; i++) {
  76481. var p = points.elements[i];
  76482. var p1;
  76483. if ((i + 1) > points.elements.length - 1) {
  76484. p1 = points.elements[0];
  76485. }
  76486. else {
  76487. p1 = points.elements[i + 1];
  76488. }
  76489. positions.push(p.x, 0, p.y);
  76490. positions.push(p.x, -depth, p.y);
  76491. positions.push(p1.x, 0, p1.y);
  76492. positions.push(p1.x, -depth, p1.y);
  76493. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  76494. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  76495. var v3 = v2.subtract(v1);
  76496. var v4 = new BABYLON.Vector3(0, 1, 0);
  76497. var vn = BABYLON.Vector3.Cross(v3, v4);
  76498. vn = vn.normalize();
  76499. uvs.push(ulength / bounds.width, 0);
  76500. uvs.push(ulength / bounds.width, 1);
  76501. ulength += v3.length();
  76502. uvs.push((ulength / bounds.width), 0);
  76503. uvs.push((ulength / bounds.width), 1);
  76504. if (!flip) {
  76505. normals.push(-vn.x, -vn.y, -vn.z);
  76506. normals.push(-vn.x, -vn.y, -vn.z);
  76507. normals.push(-vn.x, -vn.y, -vn.z);
  76508. normals.push(-vn.x, -vn.y, -vn.z);
  76509. indices.push(StartIndex);
  76510. indices.push(StartIndex + 1);
  76511. indices.push(StartIndex + 2);
  76512. indices.push(StartIndex + 1);
  76513. indices.push(StartIndex + 3);
  76514. indices.push(StartIndex + 2);
  76515. }
  76516. else {
  76517. normals.push(vn.x, vn.y, vn.z);
  76518. normals.push(vn.x, vn.y, vn.z);
  76519. normals.push(vn.x, vn.y, vn.z);
  76520. normals.push(vn.x, vn.y, vn.z);
  76521. indices.push(StartIndex);
  76522. indices.push(StartIndex + 2);
  76523. indices.push(StartIndex + 1);
  76524. indices.push(StartIndex + 1);
  76525. indices.push(StartIndex + 2);
  76526. indices.push(StartIndex + 3);
  76527. }
  76528. StartIndex += 4;
  76529. }
  76530. ;
  76531. };
  76532. return PolygonMeshBuilder;
  76533. }());
  76534. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76535. })(BABYLON || (BABYLON = {}));
  76536. //# sourceMappingURL=babylon.polygonMesh.js.map
  76537. "use strict";
  76538. var BABYLON;
  76539. (function (BABYLON) {
  76540. // Unique ID when we import meshes from Babylon to CSG
  76541. var currentCSGMeshId = 0;
  76542. // # class Vertex
  76543. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76544. // one to provide additional features like texture coordinates and vertex
  76545. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76546. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76547. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76548. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76549. // is not used anywhere else.
  76550. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76551. var Vertex = /** @class */ (function () {
  76552. function Vertex(pos, normal, uv) {
  76553. this.pos = pos;
  76554. this.normal = normal;
  76555. this.uv = uv;
  76556. }
  76557. Vertex.prototype.clone = function () {
  76558. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76559. };
  76560. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76561. // orientation of a polygon is flipped.
  76562. Vertex.prototype.flip = function () {
  76563. this.normal = this.normal.scale(-1);
  76564. };
  76565. // Create a new vertex between this vertex and `other` by linearly
  76566. // interpolating all properties using a parameter of `t`. Subclasses should
  76567. // override this to interpolate additional properties.
  76568. Vertex.prototype.interpolate = function (other, t) {
  76569. 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));
  76570. };
  76571. return Vertex;
  76572. }());
  76573. // # class Plane
  76574. // Represents a plane in 3D space.
  76575. var Plane = /** @class */ (function () {
  76576. function Plane(normal, w) {
  76577. this.normal = normal;
  76578. this.w = w;
  76579. }
  76580. Plane.FromPoints = function (a, b, c) {
  76581. var v0 = c.subtract(a);
  76582. var v1 = b.subtract(a);
  76583. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76584. return null;
  76585. }
  76586. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76587. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76588. };
  76589. Plane.prototype.clone = function () {
  76590. return new Plane(this.normal.clone(), this.w);
  76591. };
  76592. Plane.prototype.flip = function () {
  76593. this.normal.scaleInPlace(-1);
  76594. this.w = -this.w;
  76595. };
  76596. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76597. // fragments in the appropriate lists. Coplanar polygons go into either
  76598. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76599. // respect to this plane. Polygons in front or in back of this plane go into
  76600. // either `front` or `back`.
  76601. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76602. var COPLANAR = 0;
  76603. var FRONT = 1;
  76604. var BACK = 2;
  76605. var SPANNING = 3;
  76606. // Classify each point as well as the entire polygon into one of the above
  76607. // four classes.
  76608. var polygonType = 0;
  76609. var types = [];
  76610. var i;
  76611. var t;
  76612. for (i = 0; i < polygon.vertices.length; i++) {
  76613. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76614. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76615. polygonType |= type;
  76616. types.push(type);
  76617. }
  76618. // Put the polygon in the correct list, splitting it when necessary.
  76619. switch (polygonType) {
  76620. case COPLANAR:
  76621. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76622. break;
  76623. case FRONT:
  76624. front.push(polygon);
  76625. break;
  76626. case BACK:
  76627. back.push(polygon);
  76628. break;
  76629. case SPANNING:
  76630. var f = [], b = [];
  76631. for (i = 0; i < polygon.vertices.length; i++) {
  76632. var j = (i + 1) % polygon.vertices.length;
  76633. var ti = types[i], tj = types[j];
  76634. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76635. if (ti !== BACK)
  76636. f.push(vi);
  76637. if (ti !== FRONT)
  76638. b.push(ti !== BACK ? vi.clone() : vi);
  76639. if ((ti | tj) === SPANNING) {
  76640. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76641. var v = vi.interpolate(vj, t);
  76642. f.push(v);
  76643. b.push(v.clone());
  76644. }
  76645. }
  76646. var poly;
  76647. if (f.length >= 3) {
  76648. poly = new Polygon(f, polygon.shared);
  76649. if (poly.plane)
  76650. front.push(poly);
  76651. }
  76652. if (b.length >= 3) {
  76653. poly = new Polygon(b, polygon.shared);
  76654. if (poly.plane)
  76655. back.push(poly);
  76656. }
  76657. break;
  76658. }
  76659. };
  76660. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76661. // point is on the plane.
  76662. Plane.EPSILON = 1e-5;
  76663. return Plane;
  76664. }());
  76665. // # class Polygon
  76666. // Represents a convex polygon. The vertices used to initialize a polygon must
  76667. // be coplanar and form a convex loop.
  76668. //
  76669. // Each convex polygon has a `shared` property, which is shared between all
  76670. // polygons that are clones of each other or were split from the same polygon.
  76671. // This can be used to define per-polygon properties (such as surface color).
  76672. var Polygon = /** @class */ (function () {
  76673. function Polygon(vertices, shared) {
  76674. this.vertices = vertices;
  76675. this.shared = shared;
  76676. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76677. }
  76678. Polygon.prototype.clone = function () {
  76679. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76680. return new Polygon(vertices, this.shared);
  76681. };
  76682. Polygon.prototype.flip = function () {
  76683. this.vertices.reverse().map(function (v) { v.flip(); });
  76684. this.plane.flip();
  76685. };
  76686. return Polygon;
  76687. }());
  76688. // # class Node
  76689. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76690. // by picking a polygon to split along. That polygon (and all other coplanar
  76691. // polygons) are added directly to that node and the other polygons are added to
  76692. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76693. // no distinction between internal and leaf nodes.
  76694. var Node = /** @class */ (function () {
  76695. function Node(polygons) {
  76696. this.plane = null;
  76697. this.front = null;
  76698. this.back = null;
  76699. this.polygons = new Array();
  76700. if (polygons) {
  76701. this.build(polygons);
  76702. }
  76703. }
  76704. Node.prototype.clone = function () {
  76705. var node = new Node();
  76706. node.plane = this.plane && this.plane.clone();
  76707. node.front = this.front && this.front.clone();
  76708. node.back = this.back && this.back.clone();
  76709. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76710. return node;
  76711. };
  76712. // Convert solid space to empty space and empty space to solid space.
  76713. Node.prototype.invert = function () {
  76714. for (var i = 0; i < this.polygons.length; i++) {
  76715. this.polygons[i].flip();
  76716. }
  76717. if (this.plane) {
  76718. this.plane.flip();
  76719. }
  76720. if (this.front) {
  76721. this.front.invert();
  76722. }
  76723. if (this.back) {
  76724. this.back.invert();
  76725. }
  76726. var temp = this.front;
  76727. this.front = this.back;
  76728. this.back = temp;
  76729. };
  76730. // Recursively remove all polygons in `polygons` that are inside this BSP
  76731. // tree.
  76732. Node.prototype.clipPolygons = function (polygons) {
  76733. if (!this.plane)
  76734. return polygons.slice();
  76735. var front = new Array(), back = new Array();
  76736. for (var i = 0; i < polygons.length; i++) {
  76737. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76738. }
  76739. if (this.front) {
  76740. front = this.front.clipPolygons(front);
  76741. }
  76742. if (this.back) {
  76743. back = this.back.clipPolygons(back);
  76744. }
  76745. else {
  76746. back = [];
  76747. }
  76748. return front.concat(back);
  76749. };
  76750. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76751. // `bsp`.
  76752. Node.prototype.clipTo = function (bsp) {
  76753. this.polygons = bsp.clipPolygons(this.polygons);
  76754. if (this.front)
  76755. this.front.clipTo(bsp);
  76756. if (this.back)
  76757. this.back.clipTo(bsp);
  76758. };
  76759. // Return a list of all polygons in this BSP tree.
  76760. Node.prototype.allPolygons = function () {
  76761. var polygons = this.polygons.slice();
  76762. if (this.front)
  76763. polygons = polygons.concat(this.front.allPolygons());
  76764. if (this.back)
  76765. polygons = polygons.concat(this.back.allPolygons());
  76766. return polygons;
  76767. };
  76768. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76769. // new polygons are filtered down to the bottom of the tree and become new
  76770. // nodes there. Each set of polygons is partitioned using the first polygon
  76771. // (no heuristic is used to pick a good split).
  76772. Node.prototype.build = function (polygons) {
  76773. if (!polygons.length)
  76774. return;
  76775. if (!this.plane)
  76776. this.plane = polygons[0].plane.clone();
  76777. var front = new Array(), back = new Array();
  76778. for (var i = 0; i < polygons.length; i++) {
  76779. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76780. }
  76781. if (front.length) {
  76782. if (!this.front)
  76783. this.front = new Node();
  76784. this.front.build(front);
  76785. }
  76786. if (back.length) {
  76787. if (!this.back)
  76788. this.back = new Node();
  76789. this.back.build(back);
  76790. }
  76791. };
  76792. return Node;
  76793. }());
  76794. var CSG = /** @class */ (function () {
  76795. function CSG() {
  76796. this.polygons = new Array();
  76797. }
  76798. // Convert BABYLON.Mesh to BABYLON.CSG
  76799. CSG.FromMesh = function (mesh) {
  76800. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76801. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76802. if (mesh instanceof BABYLON.Mesh) {
  76803. mesh.computeWorldMatrix(true);
  76804. matrix = mesh.getWorldMatrix();
  76805. meshPosition = mesh.position.clone();
  76806. meshRotation = mesh.rotation.clone();
  76807. if (mesh.rotationQuaternion) {
  76808. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76809. }
  76810. meshScaling = mesh.scaling.clone();
  76811. }
  76812. else {
  76813. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76814. }
  76815. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76816. var subMeshes = mesh.subMeshes;
  76817. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76818. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76819. vertices = [];
  76820. for (var j = 0; j < 3; j++) {
  76821. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76822. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76823. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76824. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76825. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76826. vertex = new Vertex(position, normal, uv);
  76827. vertices.push(vertex);
  76828. }
  76829. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76830. // To handle the case of degenerated triangle
  76831. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76832. if (polygon.plane)
  76833. polygons.push(polygon);
  76834. }
  76835. }
  76836. var csg = CSG.FromPolygons(polygons);
  76837. csg.matrix = matrix;
  76838. csg.position = meshPosition;
  76839. csg.rotation = meshRotation;
  76840. csg.scaling = meshScaling;
  76841. csg.rotationQuaternion = meshRotationQuaternion;
  76842. currentCSGMeshId++;
  76843. return csg;
  76844. };
  76845. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76846. CSG.FromPolygons = function (polygons) {
  76847. var csg = new CSG();
  76848. csg.polygons = polygons;
  76849. return csg;
  76850. };
  76851. CSG.prototype.clone = function () {
  76852. var csg = new CSG();
  76853. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76854. csg.copyTransformAttributes(this);
  76855. return csg;
  76856. };
  76857. CSG.prototype.union = function (csg) {
  76858. var a = new Node(this.clone().polygons);
  76859. var b = new Node(csg.clone().polygons);
  76860. a.clipTo(b);
  76861. b.clipTo(a);
  76862. b.invert();
  76863. b.clipTo(a);
  76864. b.invert();
  76865. a.build(b.allPolygons());
  76866. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76867. };
  76868. CSG.prototype.unionInPlace = function (csg) {
  76869. var a = new Node(this.polygons);
  76870. var b = new Node(csg.polygons);
  76871. a.clipTo(b);
  76872. b.clipTo(a);
  76873. b.invert();
  76874. b.clipTo(a);
  76875. b.invert();
  76876. a.build(b.allPolygons());
  76877. this.polygons = a.allPolygons();
  76878. };
  76879. CSG.prototype.subtract = function (csg) {
  76880. var a = new Node(this.clone().polygons);
  76881. var b = new Node(csg.clone().polygons);
  76882. a.invert();
  76883. a.clipTo(b);
  76884. b.clipTo(a);
  76885. b.invert();
  76886. b.clipTo(a);
  76887. b.invert();
  76888. a.build(b.allPolygons());
  76889. a.invert();
  76890. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76891. };
  76892. CSG.prototype.subtractInPlace = function (csg) {
  76893. var a = new Node(this.polygons);
  76894. var b = new Node(csg.polygons);
  76895. a.invert();
  76896. a.clipTo(b);
  76897. b.clipTo(a);
  76898. b.invert();
  76899. b.clipTo(a);
  76900. b.invert();
  76901. a.build(b.allPolygons());
  76902. a.invert();
  76903. this.polygons = a.allPolygons();
  76904. };
  76905. CSG.prototype.intersect = function (csg) {
  76906. var a = new Node(this.clone().polygons);
  76907. var b = new Node(csg.clone().polygons);
  76908. a.invert();
  76909. b.clipTo(a);
  76910. b.invert();
  76911. a.clipTo(b);
  76912. b.clipTo(a);
  76913. a.build(b.allPolygons());
  76914. a.invert();
  76915. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76916. };
  76917. CSG.prototype.intersectInPlace = function (csg) {
  76918. var a = new Node(this.polygons);
  76919. var b = new Node(csg.polygons);
  76920. a.invert();
  76921. b.clipTo(a);
  76922. b.invert();
  76923. a.clipTo(b);
  76924. b.clipTo(a);
  76925. a.build(b.allPolygons());
  76926. a.invert();
  76927. this.polygons = a.allPolygons();
  76928. };
  76929. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76930. // not modified.
  76931. CSG.prototype.inverse = function () {
  76932. var csg = this.clone();
  76933. csg.inverseInPlace();
  76934. return csg;
  76935. };
  76936. CSG.prototype.inverseInPlace = function () {
  76937. this.polygons.map(function (p) { p.flip(); });
  76938. };
  76939. // This is used to keep meshes transformations so they can be restored
  76940. // when we build back a Babylon Mesh
  76941. // NB : All CSG operations are performed in world coordinates
  76942. CSG.prototype.copyTransformAttributes = function (csg) {
  76943. this.matrix = csg.matrix;
  76944. this.position = csg.position;
  76945. this.rotation = csg.rotation;
  76946. this.scaling = csg.scaling;
  76947. this.rotationQuaternion = csg.rotationQuaternion;
  76948. return this;
  76949. };
  76950. // Build Raw mesh from CSG
  76951. // Coordinates here are in world space
  76952. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76953. var matrix = this.matrix.clone();
  76954. matrix.invert();
  76955. 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;
  76956. if (keepSubMeshes) {
  76957. // Sort Polygons, since subMeshes are indices range
  76958. polygons.sort(function (a, b) {
  76959. if (a.shared.meshId === b.shared.meshId) {
  76960. return a.shared.subMeshId - b.shared.subMeshId;
  76961. }
  76962. else {
  76963. return a.shared.meshId - b.shared.meshId;
  76964. }
  76965. });
  76966. }
  76967. for (var i = 0, il = polygons.length; i < il; i++) {
  76968. polygon = polygons[i];
  76969. // Building SubMeshes
  76970. if (!subMesh_dict[polygon.shared.meshId]) {
  76971. subMesh_dict[polygon.shared.meshId] = {};
  76972. }
  76973. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76974. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76975. indexStart: +Infinity,
  76976. indexEnd: -Infinity,
  76977. materialIndex: polygon.shared.materialIndex
  76978. };
  76979. }
  76980. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76981. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76982. polygonIndices[0] = 0;
  76983. polygonIndices[1] = j - 1;
  76984. polygonIndices[2] = j;
  76985. for (var k = 0; k < 3; k++) {
  76986. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76987. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76988. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76989. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76990. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76991. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76992. // Check if 2 points can be merged
  76993. if (!(typeof vertex_idx !== 'undefined' &&
  76994. normals[vertex_idx * 3] === localNormal.x &&
  76995. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76996. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76997. uvs[vertex_idx * 2] === uv.x &&
  76998. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76999. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  77000. uvs.push(uv.x, uv.y);
  77001. normals.push(normal.x, normal.y, normal.z);
  77002. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  77003. }
  77004. indices.push(vertex_idx);
  77005. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  77006. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  77007. currentIndex++;
  77008. }
  77009. }
  77010. }
  77011. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  77012. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  77013. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  77014. mesh.setIndices(indices, null);
  77015. if (keepSubMeshes) {
  77016. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  77017. var materialIndexOffset = 0, materialMaxIndex;
  77018. mesh.subMeshes = new Array();
  77019. for (var m in subMesh_dict) {
  77020. materialMaxIndex = -1;
  77021. for (var sm in subMesh_dict[m]) {
  77022. subMesh_obj = subMesh_dict[m][sm];
  77023. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  77024. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  77025. }
  77026. materialIndexOffset += ++materialMaxIndex;
  77027. }
  77028. }
  77029. return mesh;
  77030. };
  77031. // Build Mesh from CSG taking material and transforms into account
  77032. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  77033. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  77034. mesh.material = material;
  77035. mesh.position.copyFrom(this.position);
  77036. mesh.rotation.copyFrom(this.rotation);
  77037. if (this.rotationQuaternion) {
  77038. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  77039. }
  77040. mesh.scaling.copyFrom(this.scaling);
  77041. mesh.computeWorldMatrix(true);
  77042. return mesh;
  77043. };
  77044. return CSG;
  77045. }());
  77046. BABYLON.CSG = CSG;
  77047. })(BABYLON || (BABYLON = {}));
  77048. //# sourceMappingURL=babylon.csg.js.map
  77049. "use strict";
  77050. var BABYLON;
  77051. (function (BABYLON) {
  77052. var LensFlare = /** @class */ (function () {
  77053. function LensFlare(size, position, color, imgUrl, system) {
  77054. this.size = size;
  77055. this.position = position;
  77056. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  77057. this.color = color || new BABYLON.Color3(1, 1, 1);
  77058. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  77059. this._system = system;
  77060. system.lensFlares.push(this);
  77061. }
  77062. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  77063. return new LensFlare(size, position, color, imgUrl, system);
  77064. };
  77065. LensFlare.prototype.dispose = function () {
  77066. if (this.texture) {
  77067. this.texture.dispose();
  77068. }
  77069. // Remove from scene
  77070. var index = this._system.lensFlares.indexOf(this);
  77071. this._system.lensFlares.splice(index, 1);
  77072. };
  77073. ;
  77074. return LensFlare;
  77075. }());
  77076. BABYLON.LensFlare = LensFlare;
  77077. })(BABYLON || (BABYLON = {}));
  77078. //# sourceMappingURL=babylon.lensFlare.js.map
  77079. "use strict";
  77080. var BABYLON;
  77081. (function (BABYLON) {
  77082. var LensFlareSystem = /** @class */ (function () {
  77083. function LensFlareSystem(name, emitter, scene) {
  77084. this.name = name;
  77085. this.lensFlares = new Array();
  77086. this.borderLimit = 300;
  77087. this.viewportBorder = 0;
  77088. this.layerMask = 0x0FFFFFFF;
  77089. this._vertexBuffers = {};
  77090. this._isEnabled = true;
  77091. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77092. this._emitter = emitter;
  77093. this.id = name;
  77094. scene.lensFlareSystems.push(this);
  77095. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  77096. var engine = scene.getEngine();
  77097. // VBO
  77098. var vertices = [];
  77099. vertices.push(1, 1);
  77100. vertices.push(-1, 1);
  77101. vertices.push(-1, -1);
  77102. vertices.push(1, -1);
  77103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77104. // Indices
  77105. var indices = [];
  77106. indices.push(0);
  77107. indices.push(1);
  77108. indices.push(2);
  77109. indices.push(0);
  77110. indices.push(2);
  77111. indices.push(3);
  77112. this._indexBuffer = engine.createIndexBuffer(indices);
  77113. // Effects
  77114. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  77115. }
  77116. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  77117. get: function () {
  77118. return this._isEnabled;
  77119. },
  77120. set: function (value) {
  77121. this._isEnabled = value;
  77122. },
  77123. enumerable: true,
  77124. configurable: true
  77125. });
  77126. LensFlareSystem.prototype.getScene = function () {
  77127. return this._scene;
  77128. };
  77129. LensFlareSystem.prototype.getEmitter = function () {
  77130. return this._emitter;
  77131. };
  77132. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  77133. this._emitter = newEmitter;
  77134. };
  77135. LensFlareSystem.prototype.getEmitterPosition = function () {
  77136. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  77137. };
  77138. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  77139. var position = this.getEmitterPosition();
  77140. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  77141. this._positionX = position.x;
  77142. this._positionY = position.y;
  77143. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  77144. if (this.viewportBorder > 0) {
  77145. globalViewport.x -= this.viewportBorder;
  77146. globalViewport.y -= this.viewportBorder;
  77147. globalViewport.width += this.viewportBorder * 2;
  77148. globalViewport.height += this.viewportBorder * 2;
  77149. position.x += this.viewportBorder;
  77150. position.y += this.viewportBorder;
  77151. this._positionX += this.viewportBorder;
  77152. this._positionY += this.viewportBorder;
  77153. }
  77154. if (position.z > 0) {
  77155. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  77156. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  77157. return true;
  77158. }
  77159. return true;
  77160. }
  77161. return false;
  77162. };
  77163. LensFlareSystem.prototype._isVisible = function () {
  77164. if (!this._isEnabled || !this._scene.activeCamera) {
  77165. return false;
  77166. }
  77167. var emitterPosition = this.getEmitterPosition();
  77168. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  77169. var distance = direction.length();
  77170. direction.normalize();
  77171. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  77172. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  77173. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  77174. };
  77175. LensFlareSystem.prototype.render = function () {
  77176. if (!this._effect.isReady() || !this._scene.activeCamera)
  77177. return false;
  77178. var engine = this._scene.getEngine();
  77179. var viewport = this._scene.activeCamera.viewport;
  77180. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  77181. // Position
  77182. if (!this.computeEffectivePosition(globalViewport)) {
  77183. return false;
  77184. }
  77185. // Visibility
  77186. if (!this._isVisible()) {
  77187. return false;
  77188. }
  77189. // Intensity
  77190. var awayX;
  77191. var awayY;
  77192. if (this._positionX < this.borderLimit + globalViewport.x) {
  77193. awayX = this.borderLimit + globalViewport.x - this._positionX;
  77194. }
  77195. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  77196. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  77197. }
  77198. else {
  77199. awayX = 0;
  77200. }
  77201. if (this._positionY < this.borderLimit + globalViewport.y) {
  77202. awayY = this.borderLimit + globalViewport.y - this._positionY;
  77203. }
  77204. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  77205. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  77206. }
  77207. else {
  77208. awayY = 0;
  77209. }
  77210. var away = (awayX > awayY) ? awayX : awayY;
  77211. away -= this.viewportBorder;
  77212. if (away > this.borderLimit) {
  77213. away = this.borderLimit;
  77214. }
  77215. var intensity = 1.0 - (away / this.borderLimit);
  77216. if (intensity < 0) {
  77217. return false;
  77218. }
  77219. if (intensity > 1.0) {
  77220. intensity = 1.0;
  77221. }
  77222. if (this.viewportBorder > 0) {
  77223. globalViewport.x += this.viewportBorder;
  77224. globalViewport.y += this.viewportBorder;
  77225. globalViewport.width -= this.viewportBorder * 2;
  77226. globalViewport.height -= this.viewportBorder * 2;
  77227. this._positionX -= this.viewportBorder;
  77228. this._positionY -= this.viewportBorder;
  77229. }
  77230. // Position
  77231. var centerX = globalViewport.x + globalViewport.width / 2;
  77232. var centerY = globalViewport.y + globalViewport.height / 2;
  77233. var distX = centerX - this._positionX;
  77234. var distY = centerY - this._positionY;
  77235. // Effects
  77236. engine.enableEffect(this._effect);
  77237. engine.setState(false);
  77238. engine.setDepthBuffer(false);
  77239. // VBOs
  77240. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  77241. // Flares
  77242. for (var index = 0; index < this.lensFlares.length; index++) {
  77243. var flare = this.lensFlares[index];
  77244. engine.setAlphaMode(flare.alphaMode);
  77245. var x = centerX - (distX * flare.position);
  77246. var y = centerY - (distY * flare.position);
  77247. var cw = flare.size;
  77248. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  77249. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  77250. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  77251. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  77252. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  77253. // Texture
  77254. this._effect.setTexture("textureSampler", flare.texture);
  77255. // Color
  77256. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  77257. // Draw order
  77258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77259. }
  77260. engine.setDepthBuffer(true);
  77261. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77262. return true;
  77263. };
  77264. LensFlareSystem.prototype.dispose = function () {
  77265. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77266. if (vertexBuffer) {
  77267. vertexBuffer.dispose();
  77268. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77269. }
  77270. if (this._indexBuffer) {
  77271. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77272. this._indexBuffer = null;
  77273. }
  77274. while (this.lensFlares.length) {
  77275. this.lensFlares[0].dispose();
  77276. }
  77277. // Remove from scene
  77278. var index = this._scene.lensFlareSystems.indexOf(this);
  77279. this._scene.lensFlareSystems.splice(index, 1);
  77280. };
  77281. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  77282. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  77283. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  77284. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  77285. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  77286. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  77287. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  77288. var parsedFlare = parsedLensFlareSystem.flares[index];
  77289. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  77290. }
  77291. return lensFlareSystem;
  77292. };
  77293. LensFlareSystem.prototype.serialize = function () {
  77294. var serializationObject = {};
  77295. serializationObject.id = this.id;
  77296. serializationObject.name = this.name;
  77297. serializationObject.emitterId = this.getEmitter().id;
  77298. serializationObject.borderLimit = this.borderLimit;
  77299. serializationObject.flares = [];
  77300. for (var index = 0; index < this.lensFlares.length; index++) {
  77301. var flare = this.lensFlares[index];
  77302. serializationObject.flares.push({
  77303. size: flare.size,
  77304. position: flare.position,
  77305. color: flare.color.asArray(),
  77306. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  77307. });
  77308. }
  77309. return serializationObject;
  77310. };
  77311. return LensFlareSystem;
  77312. }());
  77313. BABYLON.LensFlareSystem = LensFlareSystem;
  77314. })(BABYLON || (BABYLON = {}));
  77315. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  77316. "use strict";
  77317. var BABYLON;
  77318. (function (BABYLON) {
  77319. /**
  77320. * This is a holder class for the physics joint created by the physics plugin.
  77321. * It holds a set of functions to control the underlying joint.
  77322. */
  77323. var PhysicsJoint = /** @class */ (function () {
  77324. function PhysicsJoint(type, jointData) {
  77325. this.type = type;
  77326. this.jointData = jointData;
  77327. jointData.nativeParams = jointData.nativeParams || {};
  77328. }
  77329. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  77330. get: function () {
  77331. return this._physicsJoint;
  77332. },
  77333. set: function (newJoint) {
  77334. if (this._physicsJoint) {
  77335. //remove from the wolrd
  77336. }
  77337. this._physicsJoint = newJoint;
  77338. },
  77339. enumerable: true,
  77340. configurable: true
  77341. });
  77342. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  77343. set: function (physicsPlugin) {
  77344. this._physicsPlugin = physicsPlugin;
  77345. },
  77346. enumerable: true,
  77347. configurable: true
  77348. });
  77349. /**
  77350. * Execute a function that is physics-plugin specific.
  77351. * @param {Function} func the function that will be executed.
  77352. * It accepts two parameters: the physics world and the physics joint.
  77353. */
  77354. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  77355. func(this._physicsPlugin.world, this._physicsJoint);
  77356. };
  77357. //TODO check if the native joints are the same
  77358. //Joint Types
  77359. PhysicsJoint.DistanceJoint = 0;
  77360. PhysicsJoint.HingeJoint = 1;
  77361. PhysicsJoint.BallAndSocketJoint = 2;
  77362. PhysicsJoint.WheelJoint = 3;
  77363. PhysicsJoint.SliderJoint = 4;
  77364. //OIMO
  77365. PhysicsJoint.PrismaticJoint = 5;
  77366. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  77367. PhysicsJoint.UniversalJoint = 6;
  77368. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  77369. //Cannon
  77370. //Similar to a Ball-Joint. Different in params
  77371. PhysicsJoint.PointToPointJoint = 8;
  77372. //Cannon only at the moment
  77373. PhysicsJoint.SpringJoint = 9;
  77374. PhysicsJoint.LockJoint = 10;
  77375. return PhysicsJoint;
  77376. }());
  77377. BABYLON.PhysicsJoint = PhysicsJoint;
  77378. /**
  77379. * A class representing a physics distance joint.
  77380. */
  77381. var DistanceJoint = /** @class */ (function (_super) {
  77382. __extends(DistanceJoint, _super);
  77383. function DistanceJoint(jointData) {
  77384. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  77385. }
  77386. /**
  77387. * Update the predefined distance.
  77388. */
  77389. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  77390. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  77391. };
  77392. return DistanceJoint;
  77393. }(PhysicsJoint));
  77394. BABYLON.DistanceJoint = DistanceJoint;
  77395. var MotorEnabledJoint = /** @class */ (function (_super) {
  77396. __extends(MotorEnabledJoint, _super);
  77397. function MotorEnabledJoint(type, jointData) {
  77398. return _super.call(this, type, jointData) || this;
  77399. }
  77400. /**
  77401. * Set the motor values.
  77402. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77403. * @param {number} force the force to apply
  77404. * @param {number} maxForce max force for this motor.
  77405. */
  77406. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  77407. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77408. };
  77409. /**
  77410. * Set the motor's limits.
  77411. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77412. */
  77413. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77414. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77415. };
  77416. return MotorEnabledJoint;
  77417. }(PhysicsJoint));
  77418. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  77419. /**
  77420. * This class represents a single hinge physics joint
  77421. */
  77422. var HingeJoint = /** @class */ (function (_super) {
  77423. __extends(HingeJoint, _super);
  77424. function HingeJoint(jointData) {
  77425. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  77426. }
  77427. /**
  77428. * Set the motor values.
  77429. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77430. * @param {number} force the force to apply
  77431. * @param {number} maxForce max force for this motor.
  77432. */
  77433. HingeJoint.prototype.setMotor = function (force, maxForce) {
  77434. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  77435. };
  77436. /**
  77437. * Set the motor's limits.
  77438. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77439. */
  77440. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  77441. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  77442. };
  77443. return HingeJoint;
  77444. }(MotorEnabledJoint));
  77445. BABYLON.HingeJoint = HingeJoint;
  77446. /**
  77447. * This class represents a dual hinge physics joint (same as wheel joint)
  77448. */
  77449. var Hinge2Joint = /** @class */ (function (_super) {
  77450. __extends(Hinge2Joint, _super);
  77451. function Hinge2Joint(jointData) {
  77452. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  77453. }
  77454. /**
  77455. * Set the motor values.
  77456. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77457. * @param {number} force the force to apply
  77458. * @param {number} maxForce max force for this motor.
  77459. * @param {motorIndex} the motor's index, 0 or 1.
  77460. */
  77461. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  77462. if (motorIndex === void 0) { motorIndex = 0; }
  77463. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  77464. };
  77465. /**
  77466. * Set the motor limits.
  77467. * Attention, this function is plugin specific. Engines won't react 100% the same.
  77468. * @param {number} upperLimit the upper limit
  77469. * @param {number} lowerLimit lower limit
  77470. * @param {motorIndex} the motor's index, 0 or 1.
  77471. */
  77472. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  77473. if (motorIndex === void 0) { motorIndex = 0; }
  77474. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  77475. };
  77476. return Hinge2Joint;
  77477. }(MotorEnabledJoint));
  77478. BABYLON.Hinge2Joint = Hinge2Joint;
  77479. })(BABYLON || (BABYLON = {}));
  77480. //# sourceMappingURL=babylon.physicsJoint.js.map
  77481. "use strict";
  77482. var BABYLON;
  77483. (function (BABYLON) {
  77484. var PhysicsImpostor = /** @class */ (function () {
  77485. function PhysicsImpostor(object, type, _options, _scene) {
  77486. if (_options === void 0) { _options = { mass: 0 }; }
  77487. var _this = this;
  77488. this.object = object;
  77489. this.type = type;
  77490. this._options = _options;
  77491. this._scene = _scene;
  77492. this._bodyUpdateRequired = false;
  77493. this._onBeforePhysicsStepCallbacks = new Array();
  77494. this._onAfterPhysicsStepCallbacks = new Array();
  77495. this._onPhysicsCollideCallbacks = [];
  77496. this._deltaPosition = BABYLON.Vector3.Zero();
  77497. this._isDisposed = false;
  77498. //temp variables for parent rotation calculations
  77499. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  77500. this._tmpQuat = new BABYLON.Quaternion();
  77501. this._tmpQuat2 = new BABYLON.Quaternion();
  77502. /**
  77503. * this function is executed by the physics engine.
  77504. */
  77505. this.beforeStep = function () {
  77506. if (!_this._physicsEngine) {
  77507. return;
  77508. }
  77509. _this.object.translate(_this._deltaPosition, -1);
  77510. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  77511. _this.object.computeWorldMatrix(false);
  77512. if (_this.object.parent && _this.object.rotationQuaternion) {
  77513. _this.getParentsRotation();
  77514. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  77515. }
  77516. else {
  77517. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  77518. }
  77519. if (!_this._options.disableBidirectionalTransformation) {
  77520. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  77521. }
  77522. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  77523. func(_this);
  77524. });
  77525. };
  77526. /**
  77527. * this function is executed by the physics engine.
  77528. */
  77529. this.afterStep = function () {
  77530. if (!_this._physicsEngine) {
  77531. return;
  77532. }
  77533. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77534. func(_this);
  77535. });
  77536. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77537. // object has now its world rotation. needs to be converted to local.
  77538. if (_this.object.parent && _this.object.rotationQuaternion) {
  77539. _this.getParentsRotation();
  77540. _this._tmpQuat.conjugateInPlace();
  77541. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77542. }
  77543. // take the position set and make it the absolute position of this object.
  77544. _this.object.setAbsolutePosition(_this.object.position);
  77545. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77546. _this.object.translate(_this._deltaPosition, 1);
  77547. };
  77548. /**
  77549. * Legacy collision detection event support
  77550. */
  77551. this.onCollideEvent = null;
  77552. //event and body object due to cannon's event-based architecture.
  77553. this.onCollide = function (e) {
  77554. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77555. return;
  77556. }
  77557. if (!_this._physicsEngine) {
  77558. return;
  77559. }
  77560. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77561. if (otherImpostor) {
  77562. // Legacy collision detection event support
  77563. if (_this.onCollideEvent) {
  77564. _this.onCollideEvent(_this, otherImpostor);
  77565. }
  77566. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77567. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77568. }).forEach(function (obj) {
  77569. obj.callback(_this, otherImpostor);
  77570. });
  77571. }
  77572. };
  77573. //sanity check!
  77574. if (!this.object) {
  77575. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77576. return;
  77577. }
  77578. //legacy support for old syntax.
  77579. if (!this._scene && object.getScene) {
  77580. this._scene = object.getScene();
  77581. }
  77582. if (!this._scene) {
  77583. return;
  77584. }
  77585. this._physicsEngine = this._scene.getPhysicsEngine();
  77586. if (!this._physicsEngine) {
  77587. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77588. }
  77589. else {
  77590. //set the object's quaternion, if not set
  77591. if (!this.object.rotationQuaternion) {
  77592. if (this.object.rotation) {
  77593. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77594. }
  77595. else {
  77596. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77597. }
  77598. }
  77599. //default options params
  77600. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77601. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77602. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77603. this._joints = [];
  77604. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77605. if (!this.object.parent || this._options.ignoreParent) {
  77606. this._init();
  77607. }
  77608. else if (this.object.parent.physicsImpostor) {
  77609. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77610. }
  77611. }
  77612. }
  77613. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77614. get: function () {
  77615. return this._isDisposed;
  77616. },
  77617. enumerable: true,
  77618. configurable: true
  77619. });
  77620. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77621. get: function () {
  77622. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77623. },
  77624. set: function (value) {
  77625. this.setMass(value);
  77626. },
  77627. enumerable: true,
  77628. configurable: true
  77629. });
  77630. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77631. get: function () {
  77632. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77633. },
  77634. set: function (value) {
  77635. if (!this._physicsEngine) {
  77636. return;
  77637. }
  77638. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77639. },
  77640. enumerable: true,
  77641. configurable: true
  77642. });
  77643. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77644. get: function () {
  77645. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77646. },
  77647. set: function (value) {
  77648. if (!this._physicsEngine) {
  77649. return;
  77650. }
  77651. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77652. },
  77653. enumerable: true,
  77654. configurable: true
  77655. });
  77656. /**
  77657. * This function will completly initialize this impostor.
  77658. * It will create a new body - but only if this mesh has no parent.
  77659. * If it has, this impostor will not be used other than to define the impostor
  77660. * of the child mesh.
  77661. */
  77662. PhysicsImpostor.prototype._init = function () {
  77663. if (!this._physicsEngine) {
  77664. return;
  77665. }
  77666. this._physicsEngine.removeImpostor(this);
  77667. this.physicsBody = null;
  77668. this._parent = this._parent || this._getPhysicsParent();
  77669. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77670. this._physicsEngine.addImpostor(this);
  77671. }
  77672. };
  77673. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77674. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77675. var parentMesh = this.object.parent;
  77676. return parentMesh.physicsImpostor;
  77677. }
  77678. return null;
  77679. };
  77680. /**
  77681. * Should a new body be generated.
  77682. */
  77683. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77684. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77685. };
  77686. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77687. this.forceUpdate();
  77688. };
  77689. /**
  77690. * Force a regeneration of this or the parent's impostor's body.
  77691. * Use under cautious - This will remove all joints already implemented.
  77692. */
  77693. PhysicsImpostor.prototype.forceUpdate = function () {
  77694. this._init();
  77695. if (this.parent && !this._options.ignoreParent) {
  77696. this.parent.forceUpdate();
  77697. }
  77698. };
  77699. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77700. /*public get mesh(): AbstractMesh {
  77701. return this._mesh;
  77702. }*/
  77703. /**
  77704. * Gets the body that holds this impostor. Either its own, or its parent.
  77705. */
  77706. get: function () {
  77707. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77708. },
  77709. /**
  77710. * Set the physics body. Used mainly by the physics engine/plugin
  77711. */
  77712. set: function (physicsBody) {
  77713. if (this._physicsBody && this._physicsEngine) {
  77714. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77715. }
  77716. this._physicsBody = physicsBody;
  77717. this.resetUpdateFlags();
  77718. },
  77719. enumerable: true,
  77720. configurable: true
  77721. });
  77722. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77723. get: function () {
  77724. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77725. },
  77726. set: function (value) {
  77727. this._parent = value;
  77728. },
  77729. enumerable: true,
  77730. configurable: true
  77731. });
  77732. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77733. this._bodyUpdateRequired = false;
  77734. };
  77735. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77736. if (this.object.getBoundingInfo) {
  77737. var q = this.object.rotationQuaternion;
  77738. //reset rotation
  77739. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77740. //calculate the world matrix with no rotation
  77741. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77742. var boundingInfo = this.object.getBoundingInfo();
  77743. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77744. //bring back the rotation
  77745. this.object.rotationQuaternion = q;
  77746. //calculate the world matrix with the new rotation
  77747. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77748. return size;
  77749. }
  77750. else {
  77751. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77752. }
  77753. };
  77754. PhysicsImpostor.prototype.getObjectCenter = function () {
  77755. if (this.object.getBoundingInfo) {
  77756. var boundingInfo = this.object.getBoundingInfo();
  77757. return boundingInfo.boundingBox.centerWorld;
  77758. }
  77759. else {
  77760. return this.object.position;
  77761. }
  77762. };
  77763. /**
  77764. * Get a specific parametes from the options parameter.
  77765. */
  77766. PhysicsImpostor.prototype.getParam = function (paramName) {
  77767. return this._options[paramName];
  77768. };
  77769. /**
  77770. * Sets a specific parameter in the options given to the physics plugin
  77771. */
  77772. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77773. this._options[paramName] = value;
  77774. this._bodyUpdateRequired = true;
  77775. };
  77776. /**
  77777. * Specifically change the body's mass option. Won't recreate the physics body object
  77778. */
  77779. PhysicsImpostor.prototype.setMass = function (mass) {
  77780. if (this.getParam("mass") !== mass) {
  77781. this.setParam("mass", mass);
  77782. }
  77783. if (this._physicsEngine) {
  77784. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77785. }
  77786. };
  77787. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77788. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77789. };
  77790. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77791. if (this._physicsEngine) {
  77792. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77793. }
  77794. };
  77795. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77796. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77797. };
  77798. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77799. if (this._physicsEngine) {
  77800. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77801. }
  77802. };
  77803. /**
  77804. * Execute a function with the physics plugin native code.
  77805. * Provide a function the will have two variables - the world object and the physics body object.
  77806. */
  77807. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77808. if (this._physicsEngine) {
  77809. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77810. }
  77811. };
  77812. /**
  77813. * Register a function that will be executed before the physics world is stepping forward.
  77814. */
  77815. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77816. this._onBeforePhysicsStepCallbacks.push(func);
  77817. };
  77818. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77819. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77820. if (index > -1) {
  77821. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77822. }
  77823. else {
  77824. BABYLON.Tools.Warn("Function to remove was not found");
  77825. }
  77826. };
  77827. /**
  77828. * Register a function that will be executed after the physics step
  77829. */
  77830. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77831. this._onAfterPhysicsStepCallbacks.push(func);
  77832. };
  77833. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77834. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77835. if (index > -1) {
  77836. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77837. }
  77838. else {
  77839. BABYLON.Tools.Warn("Function to remove was not found");
  77840. }
  77841. };
  77842. /**
  77843. * register a function that will be executed when this impostor collides against a different body.
  77844. */
  77845. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77846. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77847. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77848. };
  77849. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77850. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77851. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77852. if (index > -1) {
  77853. this._onPhysicsCollideCallbacks.splice(index, 1);
  77854. }
  77855. else {
  77856. BABYLON.Tools.Warn("Function to remove was not found");
  77857. }
  77858. };
  77859. PhysicsImpostor.prototype.getParentsRotation = function () {
  77860. var parent = this.object.parent;
  77861. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77862. while (parent) {
  77863. if (parent.rotationQuaternion) {
  77864. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77865. }
  77866. else {
  77867. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77868. }
  77869. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77870. parent = parent.parent;
  77871. }
  77872. return this._tmpQuat;
  77873. };
  77874. /**
  77875. * Apply a force
  77876. */
  77877. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77878. if (this._physicsEngine) {
  77879. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77880. }
  77881. return this;
  77882. };
  77883. /**
  77884. * Apply an impulse
  77885. */
  77886. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77887. if (this._physicsEngine) {
  77888. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77889. }
  77890. return this;
  77891. };
  77892. /**
  77893. * A help function to create a joint.
  77894. */
  77895. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77896. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77897. this.addJoint(otherImpostor, joint);
  77898. return this;
  77899. };
  77900. /**
  77901. * Add a joint to this impostor with a different impostor.
  77902. */
  77903. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77904. this._joints.push({
  77905. otherImpostor: otherImpostor,
  77906. joint: joint
  77907. });
  77908. if (this._physicsEngine) {
  77909. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77910. }
  77911. return this;
  77912. };
  77913. /**
  77914. * Will keep this body still, in a sleep mode.
  77915. */
  77916. PhysicsImpostor.prototype.sleep = function () {
  77917. if (this._physicsEngine) {
  77918. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77919. }
  77920. return this;
  77921. };
  77922. /**
  77923. * Wake the body up.
  77924. */
  77925. PhysicsImpostor.prototype.wakeUp = function () {
  77926. if (this._physicsEngine) {
  77927. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77928. }
  77929. return this;
  77930. };
  77931. PhysicsImpostor.prototype.clone = function (newObject) {
  77932. if (!newObject)
  77933. return null;
  77934. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77935. };
  77936. PhysicsImpostor.prototype.dispose = function () {
  77937. var _this = this;
  77938. //no dispose if no physics engine is available.
  77939. if (!this._physicsEngine) {
  77940. return;
  77941. }
  77942. this._joints.forEach(function (j) {
  77943. if (_this._physicsEngine) {
  77944. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77945. }
  77946. });
  77947. //dispose the physics body
  77948. this._physicsEngine.removeImpostor(this);
  77949. if (this.parent) {
  77950. this.parent.forceUpdate();
  77951. }
  77952. else {
  77953. /*this._object.getChildMeshes().forEach(function(mesh) {
  77954. if (mesh.physicsImpostor) {
  77955. if (disposeChildren) {
  77956. mesh.physicsImpostor.dispose();
  77957. mesh.physicsImpostor = null;
  77958. }
  77959. }
  77960. })*/
  77961. }
  77962. this._isDisposed = true;
  77963. };
  77964. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77965. this._deltaPosition.copyFrom(position);
  77966. };
  77967. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77968. if (!this._deltaRotation) {
  77969. this._deltaRotation = new BABYLON.Quaternion();
  77970. }
  77971. this._deltaRotation.copyFrom(rotation);
  77972. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77973. };
  77974. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77975. if (this._physicsEngine) {
  77976. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77977. }
  77978. return this;
  77979. };
  77980. PhysicsImpostor.prototype.getRadius = function () {
  77981. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77982. };
  77983. /**
  77984. * Sync a bone with this impostor
  77985. * @param bone The bone to sync to the impostor.
  77986. * @param boneMesh The mesh that the bone is influencing.
  77987. * @param jointPivot The pivot of the joint / bone in local space.
  77988. * @param distToJoint Optional distance from the impostor to the joint.
  77989. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77990. */
  77991. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77992. var tempVec = PhysicsImpostor._tmpVecs[0];
  77993. var mesh = this.object;
  77994. if (mesh.rotationQuaternion) {
  77995. if (adjustRotation) {
  77996. var tempQuat = PhysicsImpostor._tmpQuat;
  77997. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77998. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77999. }
  78000. else {
  78001. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  78002. }
  78003. }
  78004. tempVec.x = 0;
  78005. tempVec.y = 0;
  78006. tempVec.z = 0;
  78007. if (jointPivot) {
  78008. tempVec.x = jointPivot.x;
  78009. tempVec.y = jointPivot.y;
  78010. tempVec.z = jointPivot.z;
  78011. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  78012. if (distToJoint === undefined || distToJoint === null) {
  78013. distToJoint = jointPivot.length();
  78014. }
  78015. tempVec.x *= distToJoint;
  78016. tempVec.y *= distToJoint;
  78017. tempVec.z *= distToJoint;
  78018. }
  78019. if (bone.getParent()) {
  78020. tempVec.addInPlace(mesh.getAbsolutePosition());
  78021. bone.setAbsolutePosition(tempVec, boneMesh);
  78022. }
  78023. else {
  78024. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  78025. boneMesh.position.x -= tempVec.x;
  78026. boneMesh.position.y -= tempVec.y;
  78027. boneMesh.position.z -= tempVec.z;
  78028. }
  78029. };
  78030. /**
  78031. * Sync impostor to a bone
  78032. * @param bone The bone that the impostor will be synced to.
  78033. * @param boneMesh The mesh that the bone is influencing.
  78034. * @param jointPivot The pivot of the joint / bone in local space.
  78035. * @param distToJoint Optional distance from the impostor to the joint.
  78036. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  78037. * @param boneAxis Optional vector3 axis the bone is aligned with
  78038. */
  78039. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  78040. var mesh = this.object;
  78041. if (mesh.rotationQuaternion) {
  78042. if (adjustRotation) {
  78043. var tempQuat = PhysicsImpostor._tmpQuat;
  78044. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  78045. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  78046. }
  78047. else {
  78048. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  78049. }
  78050. }
  78051. var pos = PhysicsImpostor._tmpVecs[0];
  78052. var boneDir = PhysicsImpostor._tmpVecs[1];
  78053. if (!boneAxis) {
  78054. boneAxis = PhysicsImpostor._tmpVecs[2];
  78055. boneAxis.x = 0;
  78056. boneAxis.y = 1;
  78057. boneAxis.z = 0;
  78058. }
  78059. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  78060. bone.getAbsolutePositionToRef(boneMesh, pos);
  78061. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  78062. distToJoint = jointPivot.length();
  78063. }
  78064. if (distToJoint !== undefined && distToJoint !== null) {
  78065. pos.x += boneDir.x * distToJoint;
  78066. pos.y += boneDir.y * distToJoint;
  78067. pos.z += boneDir.z * distToJoint;
  78068. }
  78069. mesh.setAbsolutePosition(pos);
  78070. };
  78071. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  78072. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  78073. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78074. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  78075. //Impostor types
  78076. PhysicsImpostor.NoImpostor = 0;
  78077. PhysicsImpostor.SphereImpostor = 1;
  78078. PhysicsImpostor.BoxImpostor = 2;
  78079. PhysicsImpostor.PlaneImpostor = 3;
  78080. PhysicsImpostor.MeshImpostor = 4;
  78081. PhysicsImpostor.CylinderImpostor = 7;
  78082. PhysicsImpostor.ParticleImpostor = 8;
  78083. PhysicsImpostor.HeightmapImpostor = 9;
  78084. return PhysicsImpostor;
  78085. }());
  78086. BABYLON.PhysicsImpostor = PhysicsImpostor;
  78087. })(BABYLON || (BABYLON = {}));
  78088. //# sourceMappingURL=babylon.physicsImpostor.js.map
  78089. "use strict";
  78090. var BABYLON;
  78091. (function (BABYLON) {
  78092. var PhysicsEngine = /** @class */ (function () {
  78093. function PhysicsEngine(gravity, _physicsPlugin) {
  78094. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  78095. this._physicsPlugin = _physicsPlugin;
  78096. //new methods and parameters
  78097. this._impostors = [];
  78098. this._joints = [];
  78099. if (!this._physicsPlugin.isSupported()) {
  78100. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  78101. + "Please make sure it is included.");
  78102. }
  78103. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  78104. this.setGravity(gravity);
  78105. this.setTimeStep();
  78106. }
  78107. PhysicsEngine.prototype.setGravity = function (gravity) {
  78108. this.gravity = gravity;
  78109. this._physicsPlugin.setGravity(this.gravity);
  78110. };
  78111. /**
  78112. * Set the time step of the physics engine.
  78113. * default is 1/60.
  78114. * To slow it down, enter 1/600 for example.
  78115. * To speed it up, 1/30
  78116. * @param {number} newTimeStep the new timestep to apply to this world.
  78117. */
  78118. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  78119. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  78120. this._physicsPlugin.setTimeStep(newTimeStep);
  78121. };
  78122. /**
  78123. * Get the time step of the physics engine.
  78124. */
  78125. PhysicsEngine.prototype.getTimeStep = function () {
  78126. return this._physicsPlugin.getTimeStep();
  78127. };
  78128. PhysicsEngine.prototype.dispose = function () {
  78129. this._impostors.forEach(function (impostor) {
  78130. impostor.dispose();
  78131. });
  78132. this._physicsPlugin.dispose();
  78133. };
  78134. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  78135. return this._physicsPlugin.name;
  78136. };
  78137. /**
  78138. * Adding a new impostor for the impostor tracking.
  78139. * This will be done by the impostor itself.
  78140. * @param {PhysicsImpostor} impostor the impostor to add
  78141. */
  78142. PhysicsEngine.prototype.addImpostor = function (impostor) {
  78143. impostor.uniqueId = this._impostors.push(impostor);
  78144. //if no parent, generate the body
  78145. if (!impostor.parent) {
  78146. this._physicsPlugin.generatePhysicsBody(impostor);
  78147. }
  78148. };
  78149. /**
  78150. * Remove an impostor from the engine.
  78151. * This impostor and its mesh will not longer be updated by the physics engine.
  78152. * @param {PhysicsImpostor} impostor the impostor to remove
  78153. */
  78154. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  78155. var index = this._impostors.indexOf(impostor);
  78156. if (index > -1) {
  78157. var removed = this._impostors.splice(index, 1);
  78158. //Is it needed?
  78159. if (removed.length) {
  78160. //this will also remove it from the world.
  78161. removed[0].physicsBody = null;
  78162. }
  78163. }
  78164. };
  78165. /**
  78166. * Add a joint to the physics engine
  78167. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  78168. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  78169. * @param {PhysicsJoint} the joint that will connect both impostors.
  78170. */
  78171. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  78172. var impostorJoint = {
  78173. mainImpostor: mainImpostor,
  78174. connectedImpostor: connectedImpostor,
  78175. joint: joint
  78176. };
  78177. joint.physicsPlugin = this._physicsPlugin;
  78178. this._joints.push(impostorJoint);
  78179. this._physicsPlugin.generateJoint(impostorJoint);
  78180. };
  78181. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  78182. var matchingJoints = this._joints.filter(function (impostorJoint) {
  78183. return (impostorJoint.connectedImpostor === connectedImpostor
  78184. && impostorJoint.joint === joint
  78185. && impostorJoint.mainImpostor === mainImpostor);
  78186. });
  78187. if (matchingJoints.length) {
  78188. this._physicsPlugin.removeJoint(matchingJoints[0]);
  78189. //TODO remove it from the list as well
  78190. }
  78191. };
  78192. /**
  78193. * Called by the scene. no need to call it.
  78194. */
  78195. PhysicsEngine.prototype._step = function (delta) {
  78196. var _this = this;
  78197. //check if any mesh has no body / requires an update
  78198. this._impostors.forEach(function (impostor) {
  78199. if (impostor.isBodyInitRequired()) {
  78200. _this._physicsPlugin.generatePhysicsBody(impostor);
  78201. }
  78202. });
  78203. if (delta > 0.1) {
  78204. delta = 0.1;
  78205. }
  78206. else if (delta <= 0) {
  78207. delta = 1.0 / 60.0;
  78208. }
  78209. this._physicsPlugin.executeStep(delta, this._impostors);
  78210. };
  78211. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  78212. return this._physicsPlugin;
  78213. };
  78214. PhysicsEngine.prototype.getImpostors = function () {
  78215. return this._impostors;
  78216. };
  78217. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  78218. for (var i = 0; i < this._impostors.length; ++i) {
  78219. if (this._impostors[i].object === object) {
  78220. return this._impostors[i];
  78221. }
  78222. }
  78223. return null;
  78224. };
  78225. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  78226. for (var i = 0; i < this._impostors.length; ++i) {
  78227. if (this._impostors[i].physicsBody === body) {
  78228. return this._impostors[i];
  78229. }
  78230. }
  78231. return null;
  78232. };
  78233. // Statics
  78234. PhysicsEngine.Epsilon = 0.001;
  78235. return PhysicsEngine;
  78236. }());
  78237. BABYLON.PhysicsEngine = PhysicsEngine;
  78238. })(BABYLON || (BABYLON = {}));
  78239. //# sourceMappingURL=babylon.physicsEngine.js.map
  78240. "use strict";
  78241. var BABYLON;
  78242. (function (BABYLON) {
  78243. var PhysicsHelper = /** @class */ (function () {
  78244. function PhysicsHelper(scene) {
  78245. this._scene = scene;
  78246. this._physicsEngine = this._scene.getPhysicsEngine();
  78247. if (!this._physicsEngine) {
  78248. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  78249. }
  78250. }
  78251. /**
  78252. * @param {Vector3} origin the origin of the explosion
  78253. * @param {number} radius the explosion radius
  78254. * @param {number} strength the explosion strength
  78255. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78256. */
  78257. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  78258. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78259. if (!this._physicsEngine) {
  78260. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  78261. return null;
  78262. }
  78263. var impostors = this._physicsEngine.getImpostors();
  78264. if (impostors.length === 0) {
  78265. return null;
  78266. }
  78267. var event = new PhysicsRadialExplosionEvent(this._scene);
  78268. impostors.forEach(function (impostor) {
  78269. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78270. if (!impostorForceAndContactPoint) {
  78271. return;
  78272. }
  78273. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78274. });
  78275. event.dispose(false);
  78276. return event;
  78277. };
  78278. /**
  78279. * @param {Vector3} origin the origin of the explosion
  78280. * @param {number} radius the explosion radius
  78281. * @param {number} strength the explosion strength
  78282. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78283. */
  78284. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  78285. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78286. if (!this._physicsEngine) {
  78287. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78288. return null;
  78289. }
  78290. var impostors = this._physicsEngine.getImpostors();
  78291. if (impostors.length === 0) {
  78292. return null;
  78293. }
  78294. var event = new PhysicsRadialExplosionEvent(this._scene);
  78295. impostors.forEach(function (impostor) {
  78296. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  78297. if (!impostorForceAndContactPoint) {
  78298. return;
  78299. }
  78300. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78301. });
  78302. event.dispose(false);
  78303. return event;
  78304. };
  78305. /**
  78306. * @param {Vector3} origin the origin of the explosion
  78307. * @param {number} radius the explosion radius
  78308. * @param {number} strength the explosion strength
  78309. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  78310. */
  78311. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  78312. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78313. if (!this._physicsEngine) {
  78314. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78315. return null;
  78316. }
  78317. var impostors = this._physicsEngine.getImpostors();
  78318. if (impostors.length === 0) {
  78319. return null;
  78320. }
  78321. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  78322. event.dispose(false);
  78323. return event;
  78324. };
  78325. /**
  78326. * @param {Vector3} origin the origin of the updraft
  78327. * @param {number} radius the radius of the updraft
  78328. * @param {number} strength the strength of the updraft
  78329. * @param {number} height the height of the updraft
  78330. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  78331. */
  78332. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  78333. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  78334. if (!this._physicsEngine) {
  78335. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78336. return null;
  78337. }
  78338. if (this._physicsEngine.getImpostors().length === 0) {
  78339. return null;
  78340. }
  78341. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  78342. event.dispose(false);
  78343. return event;
  78344. };
  78345. /**
  78346. * @param {Vector3} origin the of the vortex
  78347. * @param {number} radius the radius of the vortex
  78348. * @param {number} strength the strength of the vortex
  78349. * @param {number} height the height of the vortex
  78350. */
  78351. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  78352. if (!this._physicsEngine) {
  78353. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  78354. return null;
  78355. }
  78356. if (this._physicsEngine.getImpostors().length === 0) {
  78357. return null;
  78358. }
  78359. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  78360. event.dispose(false);
  78361. return event;
  78362. };
  78363. return PhysicsHelper;
  78364. }());
  78365. BABYLON.PhysicsHelper = PhysicsHelper;
  78366. /***** Radial explosion *****/
  78367. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  78368. function PhysicsRadialExplosionEvent(scene) {
  78369. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  78370. this._rays = [];
  78371. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  78372. this._scene = scene;
  78373. }
  78374. /**
  78375. * Returns the data related to the radial explosion event (sphere & rays).
  78376. * @returns {PhysicsRadialExplosionEventData}
  78377. */
  78378. PhysicsRadialExplosionEvent.prototype.getData = function () {
  78379. this._dataFetched = true;
  78380. return {
  78381. sphere: this._sphere,
  78382. rays: this._rays,
  78383. };
  78384. };
  78385. /**
  78386. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  78387. * @param impostor
  78388. * @param {Vector3} origin the origin of the explosion
  78389. * @param {number} radius the explosion radius
  78390. * @param {number} strength the explosion strength
  78391. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  78392. * @returns {Nullable<PhysicsForceAndContactPoint>}
  78393. */
  78394. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  78395. if (impostor.mass === 0) {
  78396. return null;
  78397. }
  78398. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  78399. return null;
  78400. }
  78401. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78402. return null;
  78403. }
  78404. var impostorObjectCenter = impostor.getObjectCenter();
  78405. var direction = impostorObjectCenter.subtract(origin);
  78406. var ray = new BABYLON.Ray(origin, direction, radius);
  78407. this._rays.push(ray);
  78408. var hit = ray.intersectsMesh(impostor.object);
  78409. var contactPoint = hit.pickedPoint;
  78410. if (!contactPoint) {
  78411. return null;
  78412. }
  78413. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  78414. if (distanceFromOrigin > radius) {
  78415. return null;
  78416. }
  78417. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  78418. ? strength
  78419. : strength * (1 - (distanceFromOrigin / radius));
  78420. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78421. return { force: force, contactPoint: contactPoint };
  78422. };
  78423. /**
  78424. * Disposes the sphere.
  78425. * @param {bolean} force
  78426. */
  78427. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  78428. var _this = this;
  78429. if (force === void 0) { force = true; }
  78430. if (force) {
  78431. this._sphere.dispose();
  78432. }
  78433. else {
  78434. setTimeout(function () {
  78435. if (!_this._dataFetched) {
  78436. _this._sphere.dispose();
  78437. }
  78438. }, 0);
  78439. }
  78440. };
  78441. /*** Helpers ***/
  78442. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  78443. if (!this._sphere) {
  78444. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  78445. this._sphere.isVisible = false;
  78446. }
  78447. };
  78448. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  78449. var impostorObject = impostor.object;
  78450. this._prepareSphere();
  78451. this._sphere.position = origin;
  78452. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  78453. this._sphere._updateBoundingInfo();
  78454. this._sphere.computeWorldMatrix(true);
  78455. return this._sphere.intersectsMesh(impostorObject, true);
  78456. };
  78457. return PhysicsRadialExplosionEvent;
  78458. }());
  78459. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  78460. /***** Gravitational Field *****/
  78461. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  78462. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  78463. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  78464. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78465. this._physicsHelper = physicsHelper;
  78466. this._scene = scene;
  78467. this._origin = origin;
  78468. this._radius = radius;
  78469. this._strength = strength;
  78470. this._falloff = falloff;
  78471. this._tickCallback = this._tick.bind(this);
  78472. }
  78473. /**
  78474. * Returns the data related to the gravitational field event (sphere).
  78475. * @returns {PhysicsGravitationalFieldEventData}
  78476. */
  78477. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  78478. this._dataFetched = true;
  78479. return {
  78480. sphere: this._sphere,
  78481. };
  78482. };
  78483. /**
  78484. * Enables the gravitational field.
  78485. */
  78486. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  78487. this._tickCallback.call(this);
  78488. this._scene.registerBeforeRender(this._tickCallback);
  78489. };
  78490. /**
  78491. * Disables the gravitational field.
  78492. */
  78493. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  78494. this._scene.unregisterBeforeRender(this._tickCallback);
  78495. };
  78496. /**
  78497. * Disposes the sphere.
  78498. * @param {bolean} force
  78499. */
  78500. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  78501. var _this = this;
  78502. if (force === void 0) { force = true; }
  78503. if (force) {
  78504. this._sphere.dispose();
  78505. }
  78506. else {
  78507. setTimeout(function () {
  78508. if (!_this._dataFetched) {
  78509. _this._sphere.dispose();
  78510. }
  78511. }, 0);
  78512. }
  78513. };
  78514. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  78515. // Since the params won't change, we fetch the event only once
  78516. if (this._sphere) {
  78517. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78518. }
  78519. else {
  78520. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  78521. if (radialExplosionEvent) {
  78522. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  78523. }
  78524. }
  78525. };
  78526. return PhysicsGravitationalFieldEvent;
  78527. }());
  78528. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  78529. /***** Updraft *****/
  78530. var PhysicsUpdraftEvent = /** @class */ (function () {
  78531. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78532. this._scene = _scene;
  78533. this._origin = _origin;
  78534. this._radius = _radius;
  78535. this._strength = _strength;
  78536. this._height = _height;
  78537. this._updraftMode = _updraftMode;
  78538. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78539. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78540. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78541. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78542. this._physicsEngine = this._scene.getPhysicsEngine();
  78543. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78544. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78545. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78546. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78547. }
  78548. this._tickCallback = this._tick.bind(this);
  78549. }
  78550. /**
  78551. * Returns the data related to the updraft event (cylinder).
  78552. * @returns {PhysicsUpdraftEventData}
  78553. */
  78554. PhysicsUpdraftEvent.prototype.getData = function () {
  78555. this._dataFetched = true;
  78556. return {
  78557. cylinder: this._cylinder,
  78558. };
  78559. };
  78560. /**
  78561. * Enables the updraft.
  78562. */
  78563. PhysicsUpdraftEvent.prototype.enable = function () {
  78564. this._tickCallback.call(this);
  78565. this._scene.registerBeforeRender(this._tickCallback);
  78566. };
  78567. /**
  78568. * Disables the cortex.
  78569. */
  78570. PhysicsUpdraftEvent.prototype.disable = function () {
  78571. this._scene.unregisterBeforeRender(this._tickCallback);
  78572. };
  78573. /**
  78574. * Disposes the sphere.
  78575. * @param {bolean} force
  78576. */
  78577. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78578. var _this = this;
  78579. if (force === void 0) { force = true; }
  78580. if (force) {
  78581. this._cylinder.dispose();
  78582. }
  78583. else {
  78584. setTimeout(function () {
  78585. if (!_this._dataFetched) {
  78586. _this._cylinder.dispose();
  78587. }
  78588. }, 0);
  78589. }
  78590. };
  78591. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78592. if (impostor.mass === 0) {
  78593. return null;
  78594. }
  78595. if (!this._intersectsWithCylinder(impostor)) {
  78596. return null;
  78597. }
  78598. var impostorObjectCenter = impostor.getObjectCenter();
  78599. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78600. var direction = this._originDirection;
  78601. }
  78602. else {
  78603. var direction = impostorObjectCenter.subtract(this._originTop);
  78604. }
  78605. var multiplier = this._strength * -1;
  78606. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78607. return { force: force, contactPoint: impostorObjectCenter };
  78608. };
  78609. PhysicsUpdraftEvent.prototype._tick = function () {
  78610. var _this = this;
  78611. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78612. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78613. if (!impostorForceAndContactPoint) {
  78614. return;
  78615. }
  78616. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78617. });
  78618. };
  78619. /*** Helpers ***/
  78620. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78621. if (!this._cylinder) {
  78622. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78623. height: this._height,
  78624. diameter: this._radius * 2,
  78625. }, this._scene);
  78626. this._cylinder.isVisible = false;
  78627. }
  78628. };
  78629. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78630. var impostorObject = impostor.object;
  78631. this._prepareCylinder();
  78632. this._cylinder.position = this._cylinderPosition;
  78633. return this._cylinder.intersectsMesh(impostorObject, true);
  78634. };
  78635. return PhysicsUpdraftEvent;
  78636. }());
  78637. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78638. /***** Vortex *****/
  78639. var PhysicsVortexEvent = /** @class */ (function () {
  78640. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78641. this._scene = _scene;
  78642. this._origin = _origin;
  78643. this._radius = _radius;
  78644. this._strength = _strength;
  78645. this._height = _height;
  78646. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78647. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78648. this._updraftMultiplier = 0.02;
  78649. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78650. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78651. this._physicsEngine = this._scene.getPhysicsEngine();
  78652. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78653. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78654. this._tickCallback = this._tick.bind(this);
  78655. }
  78656. /**
  78657. * Returns the data related to the vortex event (cylinder).
  78658. * @returns {PhysicsVortexEventData}
  78659. */
  78660. PhysicsVortexEvent.prototype.getData = function () {
  78661. this._dataFetched = true;
  78662. return {
  78663. cylinder: this._cylinder,
  78664. };
  78665. };
  78666. /**
  78667. * Enables the vortex.
  78668. */
  78669. PhysicsVortexEvent.prototype.enable = function () {
  78670. this._tickCallback.call(this);
  78671. this._scene.registerBeforeRender(this._tickCallback);
  78672. };
  78673. /**
  78674. * Disables the cortex.
  78675. */
  78676. PhysicsVortexEvent.prototype.disable = function () {
  78677. this._scene.unregisterBeforeRender(this._tickCallback);
  78678. };
  78679. /**
  78680. * Disposes the sphere.
  78681. * @param {bolean} force
  78682. */
  78683. PhysicsVortexEvent.prototype.dispose = function (force) {
  78684. var _this = this;
  78685. if (force === void 0) { force = true; }
  78686. if (force) {
  78687. this._cylinder.dispose();
  78688. }
  78689. else {
  78690. setTimeout(function () {
  78691. if (!_this._dataFetched) {
  78692. _this._cylinder.dispose();
  78693. }
  78694. }, 0);
  78695. }
  78696. };
  78697. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78698. if (impostor.mass === 0) {
  78699. return null;
  78700. }
  78701. if (!this._intersectsWithCylinder(impostor)) {
  78702. return null;
  78703. }
  78704. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  78705. return null;
  78706. }
  78707. var impostorObjectCenter = impostor.getObjectCenter();
  78708. 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)
  78709. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78710. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78711. var hit = ray.intersectsMesh(impostor.object);
  78712. var contactPoint = hit.pickedPoint;
  78713. if (!contactPoint) {
  78714. return null;
  78715. }
  78716. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78717. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78718. var directionToOrigin = contactPoint.normalize();
  78719. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78720. directionToOrigin = directionToOrigin.negate();
  78721. }
  78722. // TODO: find a more physically based solution
  78723. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78724. var forceX = directionToOrigin.x * this._strength / 8;
  78725. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78726. var forceZ = directionToOrigin.z * this._strength / 8;
  78727. }
  78728. else {
  78729. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78730. var forceY = this._originTop.y * this._updraftMultiplier;
  78731. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78732. }
  78733. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78734. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78735. return { force: force, contactPoint: impostorObjectCenter };
  78736. };
  78737. PhysicsVortexEvent.prototype._tick = function () {
  78738. var _this = this;
  78739. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78740. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78741. if (!impostorForceAndContactPoint) {
  78742. return;
  78743. }
  78744. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78745. });
  78746. };
  78747. /*** Helpers ***/
  78748. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78749. if (!this._cylinder) {
  78750. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78751. height: this._height,
  78752. diameter: this._radius * 2,
  78753. }, this._scene);
  78754. this._cylinder.isVisible = false;
  78755. }
  78756. };
  78757. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78758. var impostorObject = impostor.object;
  78759. this._prepareCylinder();
  78760. this._cylinder.position = this._cylinderPosition;
  78761. return this._cylinder.intersectsMesh(impostorObject, true);
  78762. };
  78763. return PhysicsVortexEvent;
  78764. }());
  78765. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78766. /***** Enums *****/
  78767. /**
  78768. * The strenght of the force in correspondence to the distance of the affected object
  78769. */
  78770. var PhysicsRadialImpulseFalloff;
  78771. (function (PhysicsRadialImpulseFalloff) {
  78772. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78773. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78774. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78775. /**
  78776. * The strenght of the force in correspondence to the distance of the affected object
  78777. */
  78778. var PhysicsUpdraftMode;
  78779. (function (PhysicsUpdraftMode) {
  78780. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78781. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78782. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78783. })(BABYLON || (BABYLON = {}));
  78784. //# sourceMappingURL=babylon.physicsHelper.js.map
  78785. "use strict";
  78786. var BABYLON;
  78787. (function (BABYLON) {
  78788. var CannonJSPlugin = /** @class */ (function () {
  78789. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78790. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78791. if (iterations === void 0) { iterations = 10; }
  78792. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78793. this.name = "CannonJSPlugin";
  78794. this._physicsMaterials = new Array();
  78795. this._fixedTimeStep = 1 / 60;
  78796. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78797. this.BJSCANNON = CANNON;
  78798. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78799. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78800. this._tmpPosition = BABYLON.Vector3.Zero();
  78801. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78802. this._tmpUnityRotation = new BABYLON.Quaternion();
  78803. if (!this.isSupported()) {
  78804. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78805. return;
  78806. }
  78807. this._extendNamespace();
  78808. this.world = new this.BJSCANNON.World();
  78809. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78810. this.world.solver.iterations = iterations;
  78811. }
  78812. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78813. this.world.gravity.copy(gravity);
  78814. };
  78815. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78816. this._fixedTimeStep = timeStep;
  78817. };
  78818. CannonJSPlugin.prototype.getTimeStep = function () {
  78819. return this._fixedTimeStep;
  78820. };
  78821. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78822. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78823. };
  78824. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78825. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78826. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78827. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78828. };
  78829. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78830. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78831. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78832. impostor.physicsBody.applyForce(impulse, worldPoint);
  78833. };
  78834. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78835. //parent-child relationship. Does this impostor has a parent impostor?
  78836. if (impostor.parent) {
  78837. if (impostor.physicsBody) {
  78838. this.removePhysicsBody(impostor);
  78839. //TODO is that needed?
  78840. impostor.forceUpdate();
  78841. }
  78842. return;
  78843. }
  78844. //should a new body be created for this impostor?
  78845. if (impostor.isBodyInitRequired()) {
  78846. var shape = this._createShape(impostor);
  78847. //unregister events, if body is being changed
  78848. var oldBody = impostor.physicsBody;
  78849. if (oldBody) {
  78850. this.removePhysicsBody(impostor);
  78851. }
  78852. //create the body and material
  78853. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78854. var bodyCreationObject = {
  78855. mass: impostor.getParam("mass"),
  78856. material: material
  78857. };
  78858. // A simple extend, in case native options were used.
  78859. var nativeOptions = impostor.getParam("nativeOptions");
  78860. for (var key in nativeOptions) {
  78861. if (nativeOptions.hasOwnProperty(key)) {
  78862. bodyCreationObject[key] = nativeOptions[key];
  78863. }
  78864. }
  78865. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78866. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78867. this.world.addEventListener("preStep", impostor.beforeStep);
  78868. this.world.addEventListener("postStep", impostor.afterStep);
  78869. impostor.physicsBody.addShape(shape);
  78870. this.world.add(impostor.physicsBody);
  78871. //try to keep the body moving in the right direction by taking old properties.
  78872. //Should be tested!
  78873. if (oldBody) {
  78874. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78875. impostor.physicsBody[param].copy(oldBody[param]);
  78876. });
  78877. }
  78878. this._processChildMeshes(impostor);
  78879. }
  78880. //now update the body's transformation
  78881. this._updatePhysicsBodyTransformation(impostor);
  78882. };
  78883. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78884. var _this = this;
  78885. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78886. var currentRotation = mainImpostor.object.rotationQuaternion;
  78887. if (meshChildren.length) {
  78888. var processMesh = function (localPosition, mesh) {
  78889. if (!currentRotation || !mesh.rotationQuaternion) {
  78890. return;
  78891. }
  78892. var childImpostor = mesh.getPhysicsImpostor();
  78893. if (childImpostor) {
  78894. var parent = childImpostor.parent;
  78895. if (parent !== mainImpostor) {
  78896. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78897. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78898. if (childImpostor.physicsBody) {
  78899. _this.removePhysicsBody(childImpostor);
  78900. childImpostor.physicsBody = null;
  78901. }
  78902. childImpostor.parent = mainImpostor;
  78903. childImpostor.resetUpdateFlags();
  78904. 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));
  78905. //Add the mass of the children.
  78906. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78907. }
  78908. }
  78909. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78910. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78911. };
  78912. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78913. }
  78914. };
  78915. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78916. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78917. this.world.removeEventListener("preStep", impostor.beforeStep);
  78918. this.world.removeEventListener("postStep", impostor.afterStep);
  78919. this.world.remove(impostor.physicsBody);
  78920. };
  78921. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78922. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78923. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78924. if (!mainBody || !connectedBody) {
  78925. return;
  78926. }
  78927. var constraint;
  78928. var jointData = impostorJoint.joint.jointData;
  78929. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78930. var constraintData = {
  78931. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78932. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78933. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78934. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78935. maxForce: jointData.nativeParams.maxForce,
  78936. collideConnected: !!jointData.collision
  78937. };
  78938. switch (impostorJoint.joint.type) {
  78939. case BABYLON.PhysicsJoint.HingeJoint:
  78940. case BABYLON.PhysicsJoint.Hinge2Joint:
  78941. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78942. break;
  78943. case BABYLON.PhysicsJoint.DistanceJoint:
  78944. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78945. break;
  78946. case BABYLON.PhysicsJoint.SpringJoint:
  78947. var springData = jointData;
  78948. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78949. restLength: springData.length,
  78950. stiffness: springData.stiffness,
  78951. damping: springData.damping,
  78952. localAnchorA: constraintData.pivotA,
  78953. localAnchorB: constraintData.pivotB
  78954. });
  78955. break;
  78956. case BABYLON.PhysicsJoint.LockJoint:
  78957. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78958. break;
  78959. case BABYLON.PhysicsJoint.PointToPointJoint:
  78960. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78961. default:
  78962. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78963. break;
  78964. }
  78965. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78966. constraint.collideConnected = !!jointData.collision;
  78967. impostorJoint.joint.physicsJoint = constraint;
  78968. //don't add spring as constraint, as it is not one.
  78969. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78970. this.world.addConstraint(constraint);
  78971. }
  78972. else {
  78973. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78974. constraint.applyForce();
  78975. });
  78976. }
  78977. };
  78978. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78979. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78980. };
  78981. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78982. var index;
  78983. var mat;
  78984. for (index = 0; index < this._physicsMaterials.length; index++) {
  78985. mat = this._physicsMaterials[index];
  78986. if (mat.friction === friction && mat.restitution === restitution) {
  78987. return mat;
  78988. }
  78989. }
  78990. var currentMat = new this.BJSCANNON.Material(name);
  78991. currentMat.friction = friction;
  78992. currentMat.restitution = restitution;
  78993. this._physicsMaterials.push(currentMat);
  78994. return currentMat;
  78995. };
  78996. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78997. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78998. };
  78999. CannonJSPlugin.prototype._createShape = function (impostor) {
  79000. var object = impostor.object;
  79001. var returnValue;
  79002. var extendSize = impostor.getObjectExtendSize();
  79003. switch (impostor.type) {
  79004. case BABYLON.PhysicsImpostor.SphereImpostor:
  79005. var radiusX = extendSize.x;
  79006. var radiusY = extendSize.y;
  79007. var radiusZ = extendSize.z;
  79008. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  79009. break;
  79010. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  79011. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79012. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  79013. break;
  79014. case BABYLON.PhysicsImpostor.BoxImpostor:
  79015. var box = extendSize.scale(0.5);
  79016. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  79017. break;
  79018. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79019. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  79020. returnValue = new this.BJSCANNON.Plane();
  79021. break;
  79022. case BABYLON.PhysicsImpostor.MeshImpostor:
  79023. // should transform the vertex data to world coordinates!!
  79024. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  79025. var rawFaces = object.getIndices ? object.getIndices() : [];
  79026. if (!rawVerts)
  79027. return;
  79028. // get only scale! so the object could transform correctly.
  79029. var oldPosition = object.position.clone();
  79030. var oldRotation = object.rotation && object.rotation.clone();
  79031. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  79032. object.position.copyFromFloats(0, 0, 0);
  79033. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79034. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79035. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79036. var transform = object.computeWorldMatrix(true);
  79037. // convert rawVerts to object space
  79038. var temp = new Array();
  79039. var index;
  79040. for (index = 0; index < rawVerts.length; index += 3) {
  79041. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  79042. }
  79043. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  79044. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  79045. //now set back the transformation!
  79046. object.position.copyFrom(oldPosition);
  79047. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  79048. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  79049. break;
  79050. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  79051. var oldPosition2 = object.position.clone();
  79052. var oldRotation2 = object.rotation && object.rotation.clone();
  79053. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  79054. object.position.copyFromFloats(0, 0, 0);
  79055. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  79056. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  79057. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  79058. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  79059. returnValue = this._createHeightmap(object);
  79060. object.position.copyFrom(oldPosition2);
  79061. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  79062. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  79063. object.computeWorldMatrix(true);
  79064. break;
  79065. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79066. returnValue = new this.BJSCANNON.Particle();
  79067. break;
  79068. }
  79069. return returnValue;
  79070. };
  79071. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  79072. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  79073. var transform = object.computeWorldMatrix(true);
  79074. // convert rawVerts to object space
  79075. var temp = new Array();
  79076. var index;
  79077. for (index = 0; index < pos.length; index += 3) {
  79078. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  79079. }
  79080. pos = temp;
  79081. var matrix = new Array();
  79082. //For now pointDepth will not be used and will be automatically calculated.
  79083. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  79084. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  79085. var boundingInfo = object.getBoundingInfo();
  79086. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  79087. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  79088. var elementSize = dim * 2 / arraySize;
  79089. for (var i = 0; i < pos.length; i = i + 3) {
  79090. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  79091. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  79092. var y = -pos[i + 2] + minY;
  79093. if (!matrix[x]) {
  79094. matrix[x] = [];
  79095. }
  79096. if (!matrix[x][z]) {
  79097. matrix[x][z] = y;
  79098. }
  79099. matrix[x][z] = Math.max(y, matrix[x][z]);
  79100. }
  79101. for (var x = 0; x <= arraySize; ++x) {
  79102. if (!matrix[x]) {
  79103. var loc = 1;
  79104. while (!matrix[(x + loc) % arraySize]) {
  79105. loc++;
  79106. }
  79107. matrix[x] = matrix[(x + loc) % arraySize].slice();
  79108. //console.log("missing x", x);
  79109. }
  79110. for (var z = 0; z <= arraySize; ++z) {
  79111. if (!matrix[x][z]) {
  79112. var loc = 1;
  79113. var newValue;
  79114. while (newValue === undefined) {
  79115. newValue = matrix[x][(z + loc++) % arraySize];
  79116. }
  79117. matrix[x][z] = newValue;
  79118. }
  79119. }
  79120. }
  79121. var shape = new this.BJSCANNON.Heightfield(matrix, {
  79122. elementSize: elementSize
  79123. });
  79124. //For future reference, needed for body transformation
  79125. shape.minY = minY;
  79126. return shape;
  79127. };
  79128. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  79129. var object = impostor.object;
  79130. //make sure it is updated...
  79131. object.computeWorldMatrix && object.computeWorldMatrix(true);
  79132. // The delta between the mesh position and the mesh bounding box center
  79133. var bInfo = object.getBoundingInfo();
  79134. if (!bInfo)
  79135. return;
  79136. var center = impostor.getObjectCenter();
  79137. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  79138. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  79139. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  79140. this._tmpPosition.copyFrom(center);
  79141. var quaternion = object.rotationQuaternion;
  79142. if (!quaternion) {
  79143. return;
  79144. }
  79145. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  79146. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  79147. //-90 DEG in X, precalculated
  79148. quaternion = quaternion.multiply(this._minus90X);
  79149. //Invert! (Precalculated, 90 deg in X)
  79150. //No need to clone. this will never change.
  79151. impostor.setDeltaRotation(this._plus90X);
  79152. }
  79153. //If it is a heightfield, if should be centered.
  79154. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  79155. var mesh = object;
  79156. var boundingInfo = mesh.getBoundingInfo();
  79157. //calculate the correct body position:
  79158. var rotationQuaternion = mesh.rotationQuaternion;
  79159. mesh.rotationQuaternion = this._tmpUnityRotation;
  79160. mesh.computeWorldMatrix(true);
  79161. //get original center with no rotation
  79162. var c = center.clone();
  79163. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  79164. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  79165. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  79166. mesh.setPreTransformMatrix(p);
  79167. mesh.computeWorldMatrix(true);
  79168. //calculate the translation
  79169. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  79170. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  79171. //add it inverted to the delta
  79172. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  79173. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  79174. //rotation is back
  79175. mesh.rotationQuaternion = rotationQuaternion;
  79176. mesh.setPreTransformMatrix(oldPivot);
  79177. mesh.computeWorldMatrix(true);
  79178. }
  79179. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  79180. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  79181. //this._tmpPosition.copyFrom(object.position);
  79182. }
  79183. impostor.setDeltaPosition(this._tmpDeltaPosition);
  79184. //Now update the impostor object
  79185. impostor.physicsBody.position.copy(this._tmpPosition);
  79186. impostor.physicsBody.quaternion.copy(quaternion);
  79187. };
  79188. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79189. impostor.object.position.copyFrom(impostor.physicsBody.position);
  79190. if (impostor.object.rotationQuaternion) {
  79191. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  79192. }
  79193. };
  79194. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79195. impostor.physicsBody.position.copy(newPosition);
  79196. impostor.physicsBody.quaternion.copy(newRotation);
  79197. };
  79198. CannonJSPlugin.prototype.isSupported = function () {
  79199. return this.BJSCANNON !== undefined;
  79200. };
  79201. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79202. impostor.physicsBody.velocity.copy(velocity);
  79203. };
  79204. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79205. impostor.physicsBody.angularVelocity.copy(velocity);
  79206. };
  79207. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79208. var v = impostor.physicsBody.velocity;
  79209. if (!v) {
  79210. return null;
  79211. }
  79212. return new BABYLON.Vector3(v.x, v.y, v.z);
  79213. };
  79214. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79215. var v = impostor.physicsBody.angularVelocity;
  79216. if (!v) {
  79217. return null;
  79218. }
  79219. return new BABYLON.Vector3(v.x, v.y, v.z);
  79220. };
  79221. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79222. impostor.physicsBody.mass = mass;
  79223. impostor.physicsBody.updateMassProperties();
  79224. };
  79225. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  79226. return impostor.physicsBody.mass;
  79227. };
  79228. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  79229. return impostor.physicsBody.material.friction;
  79230. };
  79231. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79232. impostor.physicsBody.material.friction = friction;
  79233. };
  79234. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79235. return impostor.physicsBody.material.restitution;
  79236. };
  79237. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79238. impostor.physicsBody.material.restitution = restitution;
  79239. };
  79240. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  79241. impostor.physicsBody.sleep();
  79242. };
  79243. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  79244. impostor.physicsBody.wakeUp();
  79245. };
  79246. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79247. joint.physicsJoint.distance = maxDistance;
  79248. };
  79249. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79250. // if (!motorIndex) {
  79251. // joint.physicsJoint.enableMotor();
  79252. // }
  79253. // }
  79254. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  79255. // if (!motorIndex) {
  79256. // joint.physicsJoint.disableMotor();
  79257. // }
  79258. // }
  79259. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79260. if (!motorIndex) {
  79261. joint.physicsJoint.enableMotor();
  79262. joint.physicsJoint.setMotorSpeed(speed);
  79263. if (maxForce) {
  79264. this.setLimit(joint, maxForce);
  79265. }
  79266. }
  79267. };
  79268. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  79269. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  79270. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  79271. };
  79272. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79273. var body = impostor.physicsBody;
  79274. mesh.position.x = body.position.x;
  79275. mesh.position.y = body.position.y;
  79276. mesh.position.z = body.position.z;
  79277. if (mesh.rotationQuaternion) {
  79278. mesh.rotationQuaternion.x = body.quaternion.x;
  79279. mesh.rotationQuaternion.y = body.quaternion.y;
  79280. mesh.rotationQuaternion.z = body.quaternion.z;
  79281. mesh.rotationQuaternion.w = body.quaternion.w;
  79282. }
  79283. };
  79284. CannonJSPlugin.prototype.getRadius = function (impostor) {
  79285. var shape = impostor.physicsBody.shapes[0];
  79286. return shape.boundingSphereRadius;
  79287. };
  79288. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79289. var shape = impostor.physicsBody.shapes[0];
  79290. result.x = shape.halfExtents.x * 2;
  79291. result.y = shape.halfExtents.y * 2;
  79292. result.z = shape.halfExtents.z * 2;
  79293. };
  79294. CannonJSPlugin.prototype.dispose = function () {
  79295. };
  79296. CannonJSPlugin.prototype._extendNamespace = function () {
  79297. //this will force cannon to execute at least one step when using interpolation
  79298. var step_tmp1 = new this.BJSCANNON.Vec3();
  79299. var Engine = this.BJSCANNON;
  79300. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  79301. maxSubSteps = maxSubSteps || 10;
  79302. timeSinceLastCalled = timeSinceLastCalled || 0;
  79303. if (timeSinceLastCalled === 0) {
  79304. this.internalStep(dt);
  79305. this.time += dt;
  79306. }
  79307. else {
  79308. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  79309. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  79310. var t0 = performance.now();
  79311. for (var i = 0; i !== internalSteps; i++) {
  79312. this.internalStep(dt);
  79313. if (performance.now() - t0 > dt * 1000) {
  79314. break;
  79315. }
  79316. }
  79317. this.time += timeSinceLastCalled;
  79318. var h = this.time % dt;
  79319. var h_div_dt = h / dt;
  79320. var interpvelo = step_tmp1;
  79321. var bodies = this.bodies;
  79322. for (var j = 0; j !== bodies.length; j++) {
  79323. var b = bodies[j];
  79324. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  79325. b.position.vsub(b.previousPosition, interpvelo);
  79326. interpvelo.scale(h_div_dt, interpvelo);
  79327. b.position.vadd(interpvelo, b.interpolatedPosition);
  79328. }
  79329. else {
  79330. b.interpolatedPosition.copy(b.position);
  79331. b.interpolatedQuaternion.copy(b.quaternion);
  79332. }
  79333. }
  79334. }
  79335. };
  79336. };
  79337. return CannonJSPlugin;
  79338. }());
  79339. BABYLON.CannonJSPlugin = CannonJSPlugin;
  79340. })(BABYLON || (BABYLON = {}));
  79341. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  79342. "use strict";
  79343. var BABYLON;
  79344. (function (BABYLON) {
  79345. var OimoJSPlugin = /** @class */ (function () {
  79346. function OimoJSPlugin(iterations) {
  79347. this.name = "OimoJSPlugin";
  79348. this._tmpImpostorsArray = [];
  79349. this._tmpPositionVector = BABYLON.Vector3.Zero();
  79350. this.BJSOIMO = OIMO;
  79351. this.world = new this.BJSOIMO.World({
  79352. iterations: iterations
  79353. });
  79354. this.world.clear();
  79355. }
  79356. OimoJSPlugin.prototype.setGravity = function (gravity) {
  79357. this.world.gravity.copy(gravity);
  79358. };
  79359. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  79360. this.world.timeStep = timeStep;
  79361. };
  79362. OimoJSPlugin.prototype.getTimeStep = function () {
  79363. return this.world.timeStep;
  79364. };
  79365. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  79366. var _this = this;
  79367. impostors.forEach(function (impostor) {
  79368. impostor.beforeStep();
  79369. });
  79370. this.world.step();
  79371. impostors.forEach(function (impostor) {
  79372. impostor.afterStep();
  79373. //update the ordered impostors array
  79374. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  79375. });
  79376. //check for collisions
  79377. var contact = this.world.contacts;
  79378. while (contact !== null) {
  79379. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  79380. contact = contact.next;
  79381. continue;
  79382. }
  79383. //is this body colliding with any other? get the impostor
  79384. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  79385. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  79386. if (!mainImpostor || !collidingImpostor) {
  79387. contact = contact.next;
  79388. continue;
  79389. }
  79390. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  79391. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  79392. contact = contact.next;
  79393. }
  79394. };
  79395. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  79396. var mass = impostor.physicsBody.mass;
  79397. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  79398. };
  79399. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  79400. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  79401. this.applyImpulse(impostor, force, contactPoint);
  79402. };
  79403. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  79404. var _this = this;
  79405. //parent-child relationship. Does this impostor has a parent impostor?
  79406. if (impostor.parent) {
  79407. if (impostor.physicsBody) {
  79408. this.removePhysicsBody(impostor);
  79409. //TODO is that needed?
  79410. impostor.forceUpdate();
  79411. }
  79412. return;
  79413. }
  79414. if (impostor.isBodyInitRequired()) {
  79415. var bodyConfig = {
  79416. name: impostor.uniqueId,
  79417. //Oimo must have mass, also for static objects.
  79418. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  79419. size: [],
  79420. type: [],
  79421. pos: [],
  79422. posShape: [],
  79423. rot: [],
  79424. rotShape: [],
  79425. move: impostor.getParam("mass") !== 0,
  79426. density: impostor.getParam("mass"),
  79427. friction: impostor.getParam("friction"),
  79428. restitution: impostor.getParam("restitution"),
  79429. //Supporting older versions of Oimo
  79430. world: this.world
  79431. };
  79432. var impostors = [impostor];
  79433. var addToArray = function (parent) {
  79434. if (!parent.getChildMeshes)
  79435. return;
  79436. parent.getChildMeshes().forEach(function (m) {
  79437. if (m.physicsImpostor) {
  79438. impostors.push(m.physicsImpostor);
  79439. //m.physicsImpostor._init();
  79440. }
  79441. });
  79442. };
  79443. addToArray(impostor.object);
  79444. var checkWithEpsilon_1 = function (value) {
  79445. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  79446. };
  79447. impostors.forEach(function (i) {
  79448. if (!i.object.rotationQuaternion) {
  79449. return;
  79450. }
  79451. //get the correct bounding box
  79452. var oldQuaternion = i.object.rotationQuaternion;
  79453. var rot = oldQuaternion.toEulerAngles();
  79454. var extendSize = i.getObjectExtendSize();
  79455. var radToDeg = 57.295779513082320876;
  79456. if (i === impostor) {
  79457. var center = impostor.getObjectCenter();
  79458. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  79459. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  79460. //Can also use Array.prototype.push.apply
  79461. bodyConfig.pos.push(center.x);
  79462. bodyConfig.pos.push(center.y);
  79463. bodyConfig.pos.push(center.z);
  79464. bodyConfig.posShape.push(0, 0, 0);
  79465. //tmp solution
  79466. bodyConfig.rot.push(rot.x * radToDeg);
  79467. bodyConfig.rot.push(rot.y * radToDeg);
  79468. bodyConfig.rot.push(rot.z * radToDeg);
  79469. bodyConfig.rotShape.push(0, 0, 0);
  79470. }
  79471. else {
  79472. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  79473. bodyConfig.posShape.push(localPosition.x);
  79474. bodyConfig.posShape.push(localPosition.y);
  79475. bodyConfig.posShape.push(localPosition.z);
  79476. bodyConfig.pos.push(0, 0, 0);
  79477. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  79478. bodyConfig.rot.push(0);
  79479. bodyConfig.rot.push(0);
  79480. bodyConfig.rot.push(0);
  79481. bodyConfig.rotShape.push(rot.x * radToDeg);
  79482. bodyConfig.rotShape.push(rot.y * radToDeg);
  79483. bodyConfig.rotShape.push(rot.z * radToDeg);
  79484. }
  79485. // register mesh
  79486. switch (i.type) {
  79487. case BABYLON.PhysicsImpostor.ParticleImpostor:
  79488. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  79489. case BABYLON.PhysicsImpostor.SphereImpostor:
  79490. var radiusX = extendSize.x;
  79491. var radiusY = extendSize.y;
  79492. var radiusZ = extendSize.z;
  79493. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  79494. bodyConfig.type.push('sphere');
  79495. //due to the way oimo works with compounds, add 3 times
  79496. bodyConfig.size.push(size);
  79497. bodyConfig.size.push(size);
  79498. bodyConfig.size.push(size);
  79499. break;
  79500. case BABYLON.PhysicsImpostor.CylinderImpostor:
  79501. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  79502. var sizeY = checkWithEpsilon_1(extendSize.y);
  79503. bodyConfig.type.push('cylinder');
  79504. bodyConfig.size.push(sizeX);
  79505. bodyConfig.size.push(sizeY);
  79506. //due to the way oimo works with compounds, add one more value.
  79507. bodyConfig.size.push(sizeY);
  79508. break;
  79509. case BABYLON.PhysicsImpostor.PlaneImpostor:
  79510. case BABYLON.PhysicsImpostor.BoxImpostor:
  79511. default:
  79512. var sizeX = checkWithEpsilon_1(extendSize.x);
  79513. var sizeY = checkWithEpsilon_1(extendSize.y);
  79514. var sizeZ = checkWithEpsilon_1(extendSize.z);
  79515. bodyConfig.type.push('box');
  79516. //if (i === impostor) {
  79517. bodyConfig.size.push(sizeX);
  79518. bodyConfig.size.push(sizeY);
  79519. bodyConfig.size.push(sizeZ);
  79520. //} else {
  79521. // bodyConfig.size.push(0,0,0);
  79522. //}
  79523. break;
  79524. }
  79525. //actually not needed, but hey...
  79526. i.object.rotationQuaternion = oldQuaternion;
  79527. });
  79528. impostor.physicsBody = this.world.add(bodyConfig);
  79529. }
  79530. else {
  79531. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  79532. }
  79533. impostor.setDeltaPosition(this._tmpPositionVector);
  79534. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  79535. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  79536. };
  79537. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  79538. //impostor.physicsBody.dispose();
  79539. //Same as : (older oimo versions)
  79540. this.world.removeRigidBody(impostor.physicsBody);
  79541. };
  79542. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79543. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79544. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79545. if (!mainBody || !connectedBody) {
  79546. return;
  79547. }
  79548. var jointData = impostorJoint.joint.jointData;
  79549. var options = jointData.nativeParams || {};
  79550. var type;
  79551. var nativeJointData = {
  79552. body1: mainBody,
  79553. body2: connectedBody,
  79554. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79555. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79556. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79557. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79558. min: options.min,
  79559. max: options.max,
  79560. collision: options.collision || jointData.collision,
  79561. spring: options.spring,
  79562. //supporting older version of Oimo
  79563. world: this.world
  79564. };
  79565. switch (impostorJoint.joint.type) {
  79566. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79567. type = "jointBall";
  79568. break;
  79569. case BABYLON.PhysicsJoint.SpringJoint:
  79570. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79571. var springData = jointData;
  79572. nativeJointData.min = springData.length || nativeJointData.min;
  79573. //Max should also be set, just make sure it is at least min
  79574. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79575. case BABYLON.PhysicsJoint.DistanceJoint:
  79576. type = "jointDistance";
  79577. nativeJointData.max = jointData.maxDistance;
  79578. break;
  79579. case BABYLON.PhysicsJoint.PrismaticJoint:
  79580. type = "jointPrisme";
  79581. break;
  79582. case BABYLON.PhysicsJoint.SliderJoint:
  79583. type = "jointSlide";
  79584. break;
  79585. case BABYLON.PhysicsJoint.WheelJoint:
  79586. type = "jointWheel";
  79587. break;
  79588. case BABYLON.PhysicsJoint.HingeJoint:
  79589. default:
  79590. type = "jointHinge";
  79591. break;
  79592. }
  79593. nativeJointData.type = type;
  79594. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  79595. };
  79596. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79597. //Bug in Oimo prevents us from disposing a joint in the playground
  79598. //joint.joint.physicsJoint.dispose();
  79599. //So we will bruteforce it!
  79600. try {
  79601. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79602. }
  79603. catch (e) {
  79604. BABYLON.Tools.Warn(e);
  79605. }
  79606. };
  79607. OimoJSPlugin.prototype.isSupported = function () {
  79608. return this.BJSOIMO !== undefined;
  79609. };
  79610. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79611. if (!impostor.physicsBody.sleeping) {
  79612. //TODO check that
  79613. /*if (impostor.physicsBody.shapes.next) {
  79614. var parentShape = this._getLastShape(impostor.physicsBody);
  79615. impostor.object.position.copyFrom(parentShape.position);
  79616. console.log(parentShape.position);
  79617. } else {*/
  79618. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79619. //}
  79620. if (impostor.object.rotationQuaternion) {
  79621. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79622. }
  79623. }
  79624. };
  79625. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79626. var body = impostor.physicsBody;
  79627. body.position.copy(newPosition);
  79628. body.orientation.copy(newRotation);
  79629. body.syncShapes();
  79630. body.awake();
  79631. };
  79632. /*private _getLastShape(body: any): any {
  79633. var lastShape = body.shapes;
  79634. while (lastShape.next) {
  79635. lastShape = lastShape.next;
  79636. }
  79637. return lastShape;
  79638. }*/
  79639. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79640. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79641. };
  79642. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79643. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79644. };
  79645. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79646. var v = impostor.physicsBody.linearVelocity;
  79647. if (!v) {
  79648. return null;
  79649. }
  79650. return new BABYLON.Vector3(v.x, v.y, v.z);
  79651. };
  79652. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79653. var v = impostor.physicsBody.angularVelocity;
  79654. if (!v) {
  79655. return null;
  79656. }
  79657. return new BABYLON.Vector3(v.x, v.y, v.z);
  79658. };
  79659. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79660. var staticBody = mass === 0;
  79661. //this will actually set the body's density and not its mass.
  79662. //But this is how oimo treats the mass variable.
  79663. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79664. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79665. };
  79666. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79667. return impostor.physicsBody.shapes.density;
  79668. };
  79669. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79670. return impostor.physicsBody.shapes.friction;
  79671. };
  79672. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79673. impostor.physicsBody.shapes.friction = friction;
  79674. };
  79675. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79676. return impostor.physicsBody.shapes.restitution;
  79677. };
  79678. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79679. impostor.physicsBody.shapes.restitution = restitution;
  79680. };
  79681. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79682. impostor.physicsBody.sleep();
  79683. };
  79684. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79685. impostor.physicsBody.awake();
  79686. };
  79687. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79688. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79689. if (minDistance !== void 0) {
  79690. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79691. }
  79692. };
  79693. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79694. //TODO separate rotational and transational motors.
  79695. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79696. if (motor) {
  79697. motor.setMotor(speed, maxForce);
  79698. }
  79699. };
  79700. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79701. //TODO separate rotational and transational motors.
  79702. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79703. if (motor) {
  79704. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79705. }
  79706. };
  79707. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79708. var body = impostor.physicsBody;
  79709. mesh.position.x = body.position.x;
  79710. mesh.position.y = body.position.y;
  79711. mesh.position.z = body.position.z;
  79712. if (mesh.rotationQuaternion) {
  79713. mesh.rotationQuaternion.x = body.orientation.x;
  79714. mesh.rotationQuaternion.y = body.orientation.y;
  79715. mesh.rotationQuaternion.z = body.orientation.z;
  79716. mesh.rotationQuaternion.w = body.orientation.s;
  79717. }
  79718. };
  79719. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79720. return impostor.physicsBody.shapes.radius;
  79721. };
  79722. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79723. var shape = impostor.physicsBody.shapes;
  79724. result.x = shape.halfWidth * 2;
  79725. result.y = shape.halfHeight * 2;
  79726. result.z = shape.halfDepth * 2;
  79727. };
  79728. OimoJSPlugin.prototype.dispose = function () {
  79729. this.world.clear();
  79730. };
  79731. return OimoJSPlugin;
  79732. }());
  79733. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79734. })(BABYLON || (BABYLON = {}));
  79735. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79736. "use strict";
  79737. var BABYLON;
  79738. (function (BABYLON) {
  79739. /*
  79740. * Based on jsTGALoader - Javascript loader for TGA file
  79741. * By Vincent Thibault
  79742. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79743. */
  79744. var TGATools = /** @class */ (function () {
  79745. function TGATools() {
  79746. }
  79747. TGATools.GetTGAHeader = function (data) {
  79748. var offset = 0;
  79749. var header = {
  79750. id_length: data[offset++],
  79751. colormap_type: data[offset++],
  79752. image_type: data[offset++],
  79753. colormap_index: data[offset++] | data[offset++] << 8,
  79754. colormap_length: data[offset++] | data[offset++] << 8,
  79755. colormap_size: data[offset++],
  79756. origin: [
  79757. data[offset++] | data[offset++] << 8,
  79758. data[offset++] | data[offset++] << 8
  79759. ],
  79760. width: data[offset++] | data[offset++] << 8,
  79761. height: data[offset++] | data[offset++] << 8,
  79762. pixel_size: data[offset++],
  79763. flags: data[offset++]
  79764. };
  79765. return header;
  79766. };
  79767. TGATools.UploadContent = function (gl, data) {
  79768. // Not enough data to contain header ?
  79769. if (data.length < 19) {
  79770. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79771. return;
  79772. }
  79773. // Read Header
  79774. var offset = 18;
  79775. var header = TGATools.GetTGAHeader(data);
  79776. // Assume it's a valid Targa file.
  79777. if (header.id_length + offset > data.length) {
  79778. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79779. return;
  79780. }
  79781. // Skip not needed data
  79782. offset += header.id_length;
  79783. var use_rle = false;
  79784. var use_pal = false;
  79785. var use_grey = false;
  79786. // Get some informations.
  79787. switch (header.image_type) {
  79788. case TGATools._TYPE_RLE_INDEXED:
  79789. use_rle = true;
  79790. case TGATools._TYPE_INDEXED:
  79791. use_pal = true;
  79792. break;
  79793. case TGATools._TYPE_RLE_RGB:
  79794. use_rle = true;
  79795. case TGATools._TYPE_RGB:
  79796. // use_rgb = true;
  79797. break;
  79798. case TGATools._TYPE_RLE_GREY:
  79799. use_rle = true;
  79800. case TGATools._TYPE_GREY:
  79801. use_grey = true;
  79802. break;
  79803. }
  79804. var pixel_data;
  79805. // var numAlphaBits = header.flags & 0xf;
  79806. var pixel_size = header.pixel_size >> 3;
  79807. var pixel_total = header.width * header.height * pixel_size;
  79808. // Read palettes
  79809. var palettes;
  79810. if (use_pal) {
  79811. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79812. }
  79813. // Read LRE
  79814. if (use_rle) {
  79815. pixel_data = new Uint8Array(pixel_total);
  79816. var c, count, i;
  79817. var localOffset = 0;
  79818. var pixels = new Uint8Array(pixel_size);
  79819. while (offset < pixel_total && localOffset < pixel_total) {
  79820. c = data[offset++];
  79821. count = (c & 0x7f) + 1;
  79822. // RLE pixels
  79823. if (c & 0x80) {
  79824. // Bind pixel tmp array
  79825. for (i = 0; i < pixel_size; ++i) {
  79826. pixels[i] = data[offset++];
  79827. }
  79828. // Copy pixel array
  79829. for (i = 0; i < count; ++i) {
  79830. pixel_data.set(pixels, localOffset + i * pixel_size);
  79831. }
  79832. localOffset += pixel_size * count;
  79833. }
  79834. else {
  79835. count *= pixel_size;
  79836. for (i = 0; i < count; ++i) {
  79837. pixel_data[localOffset + i] = data[offset++];
  79838. }
  79839. localOffset += count;
  79840. }
  79841. }
  79842. }
  79843. else {
  79844. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79845. }
  79846. // Load to texture
  79847. var x_start, y_start, x_step, y_step, y_end, x_end;
  79848. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79849. default:
  79850. case TGATools._ORIGIN_UL:
  79851. x_start = 0;
  79852. x_step = 1;
  79853. x_end = header.width;
  79854. y_start = 0;
  79855. y_step = 1;
  79856. y_end = header.height;
  79857. break;
  79858. case TGATools._ORIGIN_BL:
  79859. x_start = 0;
  79860. x_step = 1;
  79861. x_end = header.width;
  79862. y_start = header.height - 1;
  79863. y_step = -1;
  79864. y_end = -1;
  79865. break;
  79866. case TGATools._ORIGIN_UR:
  79867. x_start = header.width - 1;
  79868. x_step = -1;
  79869. x_end = -1;
  79870. y_start = 0;
  79871. y_step = 1;
  79872. y_end = header.height;
  79873. break;
  79874. case TGATools._ORIGIN_BR:
  79875. x_start = header.width - 1;
  79876. x_step = -1;
  79877. x_end = -1;
  79878. y_start = header.height - 1;
  79879. y_step = -1;
  79880. y_end = -1;
  79881. break;
  79882. }
  79883. // Load the specify method
  79884. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79885. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79886. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79887. };
  79888. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79889. var image = pixel_data, colormap = palettes;
  79890. var width = header.width, height = header.height;
  79891. var color, i = 0, x, y;
  79892. var imageData = new Uint8Array(width * height * 4);
  79893. for (y = y_start; y !== y_end; y += y_step) {
  79894. for (x = x_start; x !== x_end; x += x_step, i++) {
  79895. color = image[i];
  79896. imageData[(x + width * y) * 4 + 3] = 255;
  79897. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79898. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79899. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79900. }
  79901. }
  79902. return imageData;
  79903. };
  79904. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79905. var image = pixel_data;
  79906. var width = header.width, height = header.height;
  79907. var color, i = 0, x, y;
  79908. var imageData = new Uint8Array(width * height * 4);
  79909. for (y = y_start; y !== y_end; y += y_step) {
  79910. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79911. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79912. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79913. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79914. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79915. imageData[(x + width * y) * 4 + 0] = r;
  79916. imageData[(x + width * y) * 4 + 1] = g;
  79917. imageData[(x + width * y) * 4 + 2] = b;
  79918. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79919. }
  79920. }
  79921. return imageData;
  79922. };
  79923. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79924. var image = pixel_data;
  79925. var width = header.width, height = header.height;
  79926. var i = 0, x, y;
  79927. var imageData = new Uint8Array(width * height * 4);
  79928. for (y = y_start; y !== y_end; y += y_step) {
  79929. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79930. imageData[(x + width * y) * 4 + 3] = 255;
  79931. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79932. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79933. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79934. }
  79935. }
  79936. return imageData;
  79937. };
  79938. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79939. var image = pixel_data;
  79940. var width = header.width, height = header.height;
  79941. var i = 0, x, y;
  79942. var imageData = new Uint8Array(width * height * 4);
  79943. for (y = y_start; y !== y_end; y += y_step) {
  79944. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79945. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79946. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79947. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79948. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79949. }
  79950. }
  79951. return imageData;
  79952. };
  79953. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79954. var image = pixel_data;
  79955. var width = header.width, height = header.height;
  79956. var color, i = 0, x, y;
  79957. var imageData = new Uint8Array(width * height * 4);
  79958. for (y = y_start; y !== y_end; y += y_step) {
  79959. for (x = x_start; x !== x_end; x += x_step, i++) {
  79960. color = image[i];
  79961. imageData[(x + width * y) * 4 + 0] = color;
  79962. imageData[(x + width * y) * 4 + 1] = color;
  79963. imageData[(x + width * y) * 4 + 2] = color;
  79964. imageData[(x + width * y) * 4 + 3] = 255;
  79965. }
  79966. }
  79967. return imageData;
  79968. };
  79969. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79970. var image = pixel_data;
  79971. var width = header.width, height = header.height;
  79972. var i = 0, x, y;
  79973. var imageData = new Uint8Array(width * height * 4);
  79974. for (y = y_start; y !== y_end; y += y_step) {
  79975. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79976. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79977. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79978. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79979. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79980. }
  79981. }
  79982. return imageData;
  79983. };
  79984. //private static _TYPE_NO_DATA = 0;
  79985. TGATools._TYPE_INDEXED = 1;
  79986. TGATools._TYPE_RGB = 2;
  79987. TGATools._TYPE_GREY = 3;
  79988. TGATools._TYPE_RLE_INDEXED = 9;
  79989. TGATools._TYPE_RLE_RGB = 10;
  79990. TGATools._TYPE_RLE_GREY = 11;
  79991. TGATools._ORIGIN_MASK = 0x30;
  79992. TGATools._ORIGIN_SHIFT = 0x04;
  79993. TGATools._ORIGIN_BL = 0x00;
  79994. TGATools._ORIGIN_BR = 0x01;
  79995. TGATools._ORIGIN_UL = 0x02;
  79996. TGATools._ORIGIN_UR = 0x03;
  79997. return TGATools;
  79998. }());
  79999. BABYLON.TGATools = TGATools;
  80000. })(BABYLON || (BABYLON = {}));
  80001. //# sourceMappingURL=babylon.tga.js.map
  80002. "use strict";
  80003. var BABYLON;
  80004. (function (BABYLON) {
  80005. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  80006. // All values and structures referenced from:
  80007. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  80008. var DDS_MAGIC = 0x20534444;
  80009. var
  80010. //DDSD_CAPS = 0x1,
  80011. //DDSD_HEIGHT = 0x2,
  80012. //DDSD_WIDTH = 0x4,
  80013. //DDSD_PITCH = 0x8,
  80014. //DDSD_PIXELFORMAT = 0x1000,
  80015. DDSD_MIPMAPCOUNT = 0x20000;
  80016. //DDSD_LINEARSIZE = 0x80000,
  80017. //DDSD_DEPTH = 0x800000;
  80018. // var DDSCAPS_COMPLEX = 0x8,
  80019. // DDSCAPS_MIPMAP = 0x400000,
  80020. // DDSCAPS_TEXTURE = 0x1000;
  80021. var DDSCAPS2_CUBEMAP = 0x200;
  80022. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  80023. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  80024. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  80025. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  80026. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  80027. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  80028. // DDSCAPS2_VOLUME = 0x200000;
  80029. var
  80030. //DDPF_ALPHAPIXELS = 0x1,
  80031. //DDPF_ALPHA = 0x2,
  80032. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  80033. //DDPF_YUV = 0x200,
  80034. DDPF_LUMINANCE = 0x20000;
  80035. function FourCCToInt32(value) {
  80036. return value.charCodeAt(0) +
  80037. (value.charCodeAt(1) << 8) +
  80038. (value.charCodeAt(2) << 16) +
  80039. (value.charCodeAt(3) << 24);
  80040. }
  80041. function Int32ToFourCC(value) {
  80042. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  80043. }
  80044. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  80045. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  80046. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  80047. var FOURCC_DX10 = FourCCToInt32("DX10");
  80048. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  80049. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  80050. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  80051. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  80052. var headerLengthInt = 31; // The header length in 32 bit ints
  80053. // Offsets into the header array
  80054. var off_magic = 0;
  80055. var off_size = 1;
  80056. var off_flags = 2;
  80057. var off_height = 3;
  80058. var off_width = 4;
  80059. var off_mipmapCount = 7;
  80060. var off_pfFlags = 20;
  80061. var off_pfFourCC = 21;
  80062. var off_RGBbpp = 22;
  80063. var off_RMask = 23;
  80064. var off_GMask = 24;
  80065. var off_BMask = 25;
  80066. var off_AMask = 26;
  80067. // var off_caps1 = 27;
  80068. var off_caps2 = 28;
  80069. // var off_caps3 = 29;
  80070. // var off_caps4 = 30;
  80071. var off_dxgiFormat = 32;
  80072. ;
  80073. var DDSTools = /** @class */ (function () {
  80074. function DDSTools() {
  80075. }
  80076. DDSTools.GetDDSInfo = function (arrayBuffer) {
  80077. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80078. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  80079. var mipmapCount = 1;
  80080. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  80081. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80082. }
  80083. var fourCC = header[off_pfFourCC];
  80084. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  80085. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80086. switch (fourCC) {
  80087. case FOURCC_D3DFMT_R16G16B16A16F:
  80088. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80089. break;
  80090. case FOURCC_D3DFMT_R32G32B32A32F:
  80091. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80092. break;
  80093. case FOURCC_DX10:
  80094. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  80095. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  80096. break;
  80097. }
  80098. }
  80099. return {
  80100. width: header[off_width],
  80101. height: header[off_height],
  80102. mipmapCount: mipmapCount,
  80103. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  80104. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  80105. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  80106. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  80107. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  80108. dxgiFormat: dxgiFormat,
  80109. textureType: textureType
  80110. };
  80111. };
  80112. DDSTools._ToHalfFloat = function (value) {
  80113. if (!DDSTools._FloatView) {
  80114. DDSTools._FloatView = new Float32Array(1);
  80115. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  80116. }
  80117. DDSTools._FloatView[0] = value;
  80118. var x = DDSTools._Int32View[0];
  80119. var bits = (x >> 16) & 0x8000; /* Get the sign */
  80120. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  80121. var e = (x >> 23) & 0xff; /* Using int is faster here */
  80122. /* If zero, or denormal, or exponent underflows too much for a denormal
  80123. * half, return signed zero. */
  80124. if (e < 103) {
  80125. return bits;
  80126. }
  80127. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  80128. if (e > 142) {
  80129. bits |= 0x7c00;
  80130. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  80131. * not Inf, so make sure we set one mantissa bit too. */
  80132. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  80133. return bits;
  80134. }
  80135. /* If exponent underflows but not too much, return a denormal */
  80136. if (e < 113) {
  80137. m |= 0x0800;
  80138. /* Extra rounding may overflow and set mantissa to 0 and exponent
  80139. * to 1, which is OK. */
  80140. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  80141. return bits;
  80142. }
  80143. bits |= ((e - 112) << 10) | (m >> 1);
  80144. bits += m & 1;
  80145. return bits;
  80146. };
  80147. DDSTools._FromHalfFloat = function (value) {
  80148. var s = (value & 0x8000) >> 15;
  80149. var e = (value & 0x7C00) >> 10;
  80150. var f = value & 0x03FF;
  80151. if (e === 0) {
  80152. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  80153. }
  80154. else if (e == 0x1F) {
  80155. return f ? NaN : ((s ? -1 : 1) * Infinity);
  80156. }
  80157. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  80158. };
  80159. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80160. var destArray = new Float32Array(dataLength);
  80161. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80162. var index = 0;
  80163. for (var y = 0; y < height; y++) {
  80164. for (var x = 0; x < width; x++) {
  80165. var srcPos = (x + y * width) * 4;
  80166. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  80167. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  80168. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  80169. if (DDSTools.StoreLODInAlphaChannel) {
  80170. destArray[index + 3] = lod;
  80171. }
  80172. else {
  80173. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  80174. }
  80175. index += 4;
  80176. }
  80177. }
  80178. return destArray;
  80179. };
  80180. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80181. if (DDSTools.StoreLODInAlphaChannel) {
  80182. var destArray = new Uint16Array(dataLength);
  80183. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80184. var index = 0;
  80185. for (var y = 0; y < height; y++) {
  80186. for (var x = 0; x < width; x++) {
  80187. var srcPos = (x + y * width) * 4;
  80188. destArray[index] = srcData[srcPos];
  80189. destArray[index + 1] = srcData[srcPos + 1];
  80190. destArray[index + 2] = srcData[srcPos + 2];
  80191. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  80192. index += 4;
  80193. }
  80194. }
  80195. return destArray;
  80196. }
  80197. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  80198. };
  80199. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80200. if (DDSTools.StoreLODInAlphaChannel) {
  80201. var destArray = new Float32Array(dataLength);
  80202. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80203. var index = 0;
  80204. for (var y = 0; y < height; y++) {
  80205. for (var x = 0; x < width; x++) {
  80206. var srcPos = (x + y * width) * 4;
  80207. destArray[index] = srcData[srcPos];
  80208. destArray[index + 1] = srcData[srcPos + 1];
  80209. destArray[index + 2] = srcData[srcPos + 2];
  80210. destArray[index + 3] = lod;
  80211. index += 4;
  80212. }
  80213. }
  80214. return destArray;
  80215. }
  80216. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  80217. };
  80218. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80219. var destArray = new Uint8Array(dataLength);
  80220. var srcData = new Float32Array(arrayBuffer, dataOffset);
  80221. var index = 0;
  80222. for (var y = 0; y < height; y++) {
  80223. for (var x = 0; x < width; x++) {
  80224. var srcPos = (x + y * width) * 4;
  80225. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  80226. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  80227. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  80228. if (DDSTools.StoreLODInAlphaChannel) {
  80229. destArray[index + 3] = lod;
  80230. }
  80231. else {
  80232. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  80233. }
  80234. index += 4;
  80235. }
  80236. }
  80237. return destArray;
  80238. };
  80239. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  80240. var destArray = new Uint8Array(dataLength);
  80241. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  80242. var index = 0;
  80243. for (var y = 0; y < height; y++) {
  80244. for (var x = 0; x < width; x++) {
  80245. var srcPos = (x + y * width) * 4;
  80246. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  80247. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  80248. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  80249. if (DDSTools.StoreLODInAlphaChannel) {
  80250. destArray[index + 3] = lod;
  80251. }
  80252. else {
  80253. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  80254. }
  80255. index += 4;
  80256. }
  80257. }
  80258. return destArray;
  80259. };
  80260. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  80261. var byteArray = new Uint8Array(dataLength);
  80262. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80263. var index = 0;
  80264. for (var y = 0; y < height; y++) {
  80265. for (var x = 0; x < width; x++) {
  80266. var srcPos = (x + y * width) * 4;
  80267. byteArray[index] = srcData[srcPos + rOffset];
  80268. byteArray[index + 1] = srcData[srcPos + gOffset];
  80269. byteArray[index + 2] = srcData[srcPos + bOffset];
  80270. byteArray[index + 3] = srcData[srcPos + aOffset];
  80271. index += 4;
  80272. }
  80273. }
  80274. return byteArray;
  80275. };
  80276. DDSTools._ExtractLongWordOrder = function (value) {
  80277. if (value === 0 || value === 255 || value === -16777216) {
  80278. return 0;
  80279. }
  80280. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  80281. };
  80282. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  80283. var byteArray = new Uint8Array(dataLength);
  80284. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80285. var index = 0;
  80286. for (var y = 0; y < height; y++) {
  80287. for (var x = 0; x < width; x++) {
  80288. var srcPos = (x + y * width) * 3;
  80289. byteArray[index] = srcData[srcPos + rOffset];
  80290. byteArray[index + 1] = srcData[srcPos + gOffset];
  80291. byteArray[index + 2] = srcData[srcPos + bOffset];
  80292. index += 3;
  80293. }
  80294. }
  80295. return byteArray;
  80296. };
  80297. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  80298. var byteArray = new Uint8Array(dataLength);
  80299. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  80300. var index = 0;
  80301. for (var y = 0; y < height; y++) {
  80302. for (var x = 0; x < width; x++) {
  80303. var srcPos = (x + y * width);
  80304. byteArray[index] = srcData[srcPos];
  80305. index++;
  80306. }
  80307. }
  80308. return byteArray;
  80309. };
  80310. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  80311. if (lodIndex === void 0) { lodIndex = -1; }
  80312. var ext = engine.getCaps().s3tc;
  80313. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  80314. var fourCC, width, height, dataLength = 0, dataOffset;
  80315. var byteArray, mipmapCount, mip;
  80316. var internalFormat = 0;
  80317. var format = 0;
  80318. var blockBytes = 1;
  80319. if (header[off_magic] !== DDS_MAGIC) {
  80320. BABYLON.Tools.Error("Invalid magic number in DDS header");
  80321. return;
  80322. }
  80323. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  80324. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  80325. return;
  80326. }
  80327. if (info.isCompressed && !ext) {
  80328. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  80329. return;
  80330. }
  80331. var bpp = header[off_RGBbpp];
  80332. dataOffset = header[off_size] + 4;
  80333. var computeFormats = false;
  80334. if (info.isFourCC) {
  80335. fourCC = header[off_pfFourCC];
  80336. switch (fourCC) {
  80337. case FOURCC_DXT1:
  80338. blockBytes = 8;
  80339. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  80340. break;
  80341. case FOURCC_DXT3:
  80342. blockBytes = 16;
  80343. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  80344. break;
  80345. case FOURCC_DXT5:
  80346. blockBytes = 16;
  80347. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  80348. break;
  80349. case FOURCC_D3DFMT_R16G16B16A16F:
  80350. computeFormats = true;
  80351. break;
  80352. case FOURCC_D3DFMT_R32G32B32A32F:
  80353. computeFormats = true;
  80354. break;
  80355. case FOURCC_DX10:
  80356. // There is an additionnal header so dataOffset need to be changed
  80357. dataOffset += 5 * 4; // 5 uints
  80358. var supported = false;
  80359. switch (info.dxgiFormat) {
  80360. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  80361. computeFormats = true;
  80362. supported = true;
  80363. break;
  80364. case DXGI_FORMAT_B8G8R8X8_UNORM:
  80365. info.isRGB = true;
  80366. info.isFourCC = false;
  80367. bpp = 32;
  80368. supported = true;
  80369. break;
  80370. }
  80371. if (supported) {
  80372. break;
  80373. }
  80374. default:
  80375. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  80376. return;
  80377. }
  80378. }
  80379. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  80380. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  80381. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  80382. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  80383. if (computeFormats) {
  80384. format = engine._getWebGLTextureType(info.textureType);
  80385. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80386. }
  80387. mipmapCount = 1;
  80388. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  80389. mipmapCount = Math.max(1, header[off_mipmapCount]);
  80390. }
  80391. for (var face = 0; face < faces; face++) {
  80392. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  80393. width = header[off_width];
  80394. height = header[off_height];
  80395. for (mip = 0; mip < mipmapCount; ++mip) {
  80396. if (lodIndex === -1 || lodIndex === mip) {
  80397. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  80398. var i = (lodIndex === -1) ? mip : 0;
  80399. if (!info.isCompressed && info.isFourCC) {
  80400. dataLength = width * height * 4;
  80401. var floatArray = null;
  80402. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  80403. if (bpp === 128) {
  80404. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80405. }
  80406. else if (bpp === 64) {
  80407. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80408. }
  80409. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  80410. format = engine._getWebGLTextureType(info.textureType);
  80411. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80412. }
  80413. else {
  80414. if (bpp === 128) {
  80415. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80416. }
  80417. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  80418. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80419. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  80420. format = engine._getWebGLTextureType(info.textureType);
  80421. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  80422. }
  80423. else {
  80424. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  80425. }
  80426. }
  80427. if (floatArray) {
  80428. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  80429. }
  80430. }
  80431. else if (info.isRGB) {
  80432. if (bpp === 24) {
  80433. dataLength = width * height * 3;
  80434. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  80435. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  80436. }
  80437. else {
  80438. dataLength = width * height * 4;
  80439. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  80440. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  80441. }
  80442. }
  80443. else if (info.isLuminance) {
  80444. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  80445. var unpaddedRowSize = width;
  80446. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  80447. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  80448. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  80449. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  80450. }
  80451. else {
  80452. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  80453. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  80454. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  80455. }
  80456. }
  80457. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  80458. width *= 0.5;
  80459. height *= 0.5;
  80460. width = Math.max(1.0, width);
  80461. height = Math.max(1.0, height);
  80462. }
  80463. if (currentFace !== undefined) {
  80464. // Loading a single face
  80465. break;
  80466. }
  80467. }
  80468. };
  80469. DDSTools.StoreLODInAlphaChannel = false;
  80470. return DDSTools;
  80471. }());
  80472. BABYLON.DDSTools = DDSTools;
  80473. })(BABYLON || (BABYLON = {}));
  80474. //# sourceMappingURL=babylon.dds.js.map
  80475. "use strict";
  80476. var BABYLON;
  80477. (function (BABYLON) {
  80478. /**
  80479. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  80480. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  80481. */
  80482. var KhronosTextureContainer = /** @class */ (function () {
  80483. /**
  80484. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  80485. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  80486. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  80487. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  80488. */
  80489. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  80490. this.arrayBuffer = arrayBuffer;
  80491. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  80492. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  80493. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  80494. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  80495. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  80496. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  80497. BABYLON.Tools.Error("texture missing KTX identifier");
  80498. return;
  80499. }
  80500. // load the reset of the header in native 32 bit int
  80501. var header = new Int32Array(this.arrayBuffer, 12, 13);
  80502. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  80503. var oppositeEndianess = header[0] === 0x01020304;
  80504. // read all the header elements in order they exist in the file, without modification (sans endainness)
  80505. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  80506. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  80507. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  80508. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  80509. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  80510. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  80511. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  80512. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  80513. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  80514. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  80515. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  80516. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  80517. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  80518. if (this.glType !== 0) {
  80519. BABYLON.Tools.Error("only compressed formats currently supported");
  80520. return;
  80521. }
  80522. else {
  80523. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  80524. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  80525. }
  80526. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  80527. BABYLON.Tools.Error("only 2D textures currently supported");
  80528. return;
  80529. }
  80530. if (this.numberOfArrayElements !== 0) {
  80531. BABYLON.Tools.Error("texture arrays not currently supported");
  80532. return;
  80533. }
  80534. if (this.numberOfFaces !== facesExpected) {
  80535. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  80536. return;
  80537. }
  80538. // we now have a completely validated file, so could use existence of loadType as success
  80539. // would need to make this more elaborate & adjust checks above to support more than one load type
  80540. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80541. }
  80542. // not as fast hardware based, but will probably never need to use
  80543. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80544. return ((val & 0xFF) << 24)
  80545. | ((val & 0xFF00) << 8)
  80546. | ((val >> 8) & 0xFF00)
  80547. | ((val >> 24) & 0xFF);
  80548. };
  80549. /**
  80550. * It is assumed that the texture has already been created & is currently bound
  80551. */
  80552. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80553. switch (this.loadType) {
  80554. case KhronosTextureContainer.COMPRESSED_2D:
  80555. this._upload2DCompressedLevels(gl, loadMipmaps);
  80556. break;
  80557. case KhronosTextureContainer.TEX_2D:
  80558. case KhronosTextureContainer.COMPRESSED_3D:
  80559. case KhronosTextureContainer.TEX_3D:
  80560. }
  80561. };
  80562. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80563. // initialize width & height for level 1
  80564. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80565. var width = this.pixelWidth;
  80566. var height = this.pixelHeight;
  80567. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80568. for (var level = 0; level < mipmapCount; level++) {
  80569. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80570. for (var face = 0; face < this.numberOfFaces; face++) {
  80571. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80572. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80573. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80574. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80575. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80576. }
  80577. width = Math.max(1.0, width * 0.5);
  80578. height = Math.max(1.0, height * 0.5);
  80579. }
  80580. };
  80581. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80582. // load types
  80583. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80584. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80585. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80586. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80587. return KhronosTextureContainer;
  80588. }());
  80589. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80590. })(BABYLON || (BABYLON = {}));
  80591. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80592. "use strict";
  80593. var BABYLON;
  80594. (function (BABYLON) {
  80595. var Debug = /** @class */ (function () {
  80596. function Debug() {
  80597. }
  80598. Debug.AxesViewer = /** @class */ (function () {
  80599. function AxesViewer(scene, scaleLines) {
  80600. if (scaleLines === void 0) { scaleLines = 1; }
  80601. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80602. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80603. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80604. this.scaleLines = 1;
  80605. this.scaleLines = scaleLines;
  80606. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80607. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80608. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80609. this._xmesh.renderingGroupId = 2;
  80610. this._ymesh.renderingGroupId = 2;
  80611. this._zmesh.renderingGroupId = 2;
  80612. this._xmesh.material.checkReadyOnlyOnce = true;
  80613. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80614. this._ymesh.material.checkReadyOnlyOnce = true;
  80615. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80616. this._zmesh.material.checkReadyOnlyOnce = true;
  80617. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80618. this.scene = scene;
  80619. }
  80620. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80621. var scaleLines = this.scaleLines;
  80622. if (this._xmesh) {
  80623. this._xmesh.position.copyFrom(position);
  80624. }
  80625. if (this._ymesh) {
  80626. this._ymesh.position.copyFrom(position);
  80627. }
  80628. if (this._zmesh) {
  80629. this._zmesh.position.copyFrom(position);
  80630. }
  80631. var point2 = this._xline[1];
  80632. point2.x = xaxis.x * scaleLines;
  80633. point2.y = xaxis.y * scaleLines;
  80634. point2.z = xaxis.z * scaleLines;
  80635. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80636. point2 = this._yline[1];
  80637. point2.x = yaxis.x * scaleLines;
  80638. point2.y = yaxis.y * scaleLines;
  80639. point2.z = yaxis.z * scaleLines;
  80640. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80641. point2 = this._zline[1];
  80642. point2.x = zaxis.x * scaleLines;
  80643. point2.y = zaxis.y * scaleLines;
  80644. point2.z = zaxis.z * scaleLines;
  80645. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80646. };
  80647. AxesViewer.prototype.dispose = function () {
  80648. if (this._xmesh) {
  80649. this._xmesh.dispose();
  80650. }
  80651. if (this._ymesh) {
  80652. this._ymesh.dispose();
  80653. }
  80654. if (this._zmesh) {
  80655. this._zmesh.dispose();
  80656. }
  80657. this._xmesh = null;
  80658. this._ymesh = null;
  80659. this._zmesh = null;
  80660. this.scene = null;
  80661. };
  80662. return AxesViewer;
  80663. }());
  80664. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80665. __extends(BoneAxesViewer, _super);
  80666. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80667. if (scaleLines === void 0) { scaleLines = 1; }
  80668. var _this = _super.call(this, scene, scaleLines) || this;
  80669. _this.pos = BABYLON.Vector3.Zero();
  80670. _this.xaxis = BABYLON.Vector3.Zero();
  80671. _this.yaxis = BABYLON.Vector3.Zero();
  80672. _this.zaxis = BABYLON.Vector3.Zero();
  80673. _this.mesh = mesh;
  80674. _this.bone = bone;
  80675. return _this;
  80676. }
  80677. BoneAxesViewer.prototype.update = function () {
  80678. if (!this.mesh || !this.bone) {
  80679. return;
  80680. }
  80681. var bone = this.bone;
  80682. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80683. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80684. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80685. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80686. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80687. };
  80688. BoneAxesViewer.prototype.dispose = function () {
  80689. if (this.mesh) {
  80690. this.mesh = null;
  80691. this.bone = null;
  80692. _super.prototype.dispose.call(this);
  80693. }
  80694. };
  80695. return BoneAxesViewer;
  80696. }(Debug.AxesViewer));
  80697. Debug.PhysicsViewer = /** @class */ (function () {
  80698. function PhysicsViewer(scene) {
  80699. this._impostors = [];
  80700. this._meshes = [];
  80701. this._numMeshes = 0;
  80702. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80703. var physicEngine = this._scene.getPhysicsEngine();
  80704. if (physicEngine) {
  80705. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80706. }
  80707. }
  80708. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80709. var plugin = this._physicsEnginePlugin;
  80710. for (var i = 0; i < this._numMeshes; i++) {
  80711. var impostor = this._impostors[i];
  80712. if (!impostor) {
  80713. continue;
  80714. }
  80715. if (impostor.isDisposed) {
  80716. this.hideImpostor(this._impostors[i--]);
  80717. }
  80718. else {
  80719. var mesh = this._meshes[i];
  80720. if (mesh && plugin) {
  80721. plugin.syncMeshWithImpostor(mesh, impostor);
  80722. }
  80723. }
  80724. }
  80725. };
  80726. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80727. if (!this._scene) {
  80728. return;
  80729. }
  80730. for (var i = 0; i < this._numMeshes; i++) {
  80731. if (this._impostors[i] == impostor) {
  80732. return;
  80733. }
  80734. }
  80735. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80736. if (debugMesh) {
  80737. this._impostors[this._numMeshes] = impostor;
  80738. this._meshes[this._numMeshes] = debugMesh;
  80739. if (this._numMeshes === 0) {
  80740. this._renderFunction = this._updateDebugMeshes.bind(this);
  80741. this._scene.registerBeforeRender(this._renderFunction);
  80742. }
  80743. this._numMeshes++;
  80744. }
  80745. };
  80746. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80747. if (!impostor || !this._scene) {
  80748. return;
  80749. }
  80750. var removed = false;
  80751. for (var i = 0; i < this._numMeshes; i++) {
  80752. if (this._impostors[i] == impostor) {
  80753. var mesh = this._meshes[i];
  80754. if (!mesh) {
  80755. continue;
  80756. }
  80757. this._scene.removeMesh(mesh);
  80758. mesh.dispose();
  80759. this._numMeshes--;
  80760. if (this._numMeshes > 0) {
  80761. this._meshes[i] = this._meshes[this._numMeshes];
  80762. this._impostors[i] = this._impostors[this._numMeshes];
  80763. this._meshes[this._numMeshes] = null;
  80764. this._impostors[this._numMeshes] = null;
  80765. }
  80766. else {
  80767. this._meshes[0] = null;
  80768. this._impostors[0] = null;
  80769. }
  80770. removed = true;
  80771. break;
  80772. }
  80773. }
  80774. if (removed && this._numMeshes === 0) {
  80775. this._scene.unregisterBeforeRender(this._renderFunction);
  80776. }
  80777. };
  80778. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80779. if (!this._debugMaterial) {
  80780. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80781. this._debugMaterial.wireframe = true;
  80782. }
  80783. return this._debugMaterial;
  80784. };
  80785. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80786. if (!this._debugBoxMesh) {
  80787. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80788. this._debugBoxMesh.renderingGroupId = 1;
  80789. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80790. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80791. scene.removeMesh(this._debugBoxMesh);
  80792. }
  80793. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80794. };
  80795. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80796. if (!this._debugSphereMesh) {
  80797. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80798. this._debugSphereMesh.renderingGroupId = 1;
  80799. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80800. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80801. scene.removeMesh(this._debugSphereMesh);
  80802. }
  80803. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80804. };
  80805. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80806. var mesh = null;
  80807. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80808. mesh = this._getDebugBoxMesh(scene);
  80809. impostor.getBoxSizeToRef(mesh.scaling);
  80810. }
  80811. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80812. mesh = this._getDebugSphereMesh(scene);
  80813. var radius = impostor.getRadius();
  80814. mesh.scaling.x = radius * 2;
  80815. mesh.scaling.y = radius * 2;
  80816. mesh.scaling.z = radius * 2;
  80817. }
  80818. return mesh;
  80819. };
  80820. PhysicsViewer.prototype.dispose = function () {
  80821. for (var i = 0; i < this._numMeshes; i++) {
  80822. this.hideImpostor(this._impostors[i]);
  80823. }
  80824. if (this._debugBoxMesh) {
  80825. this._debugBoxMesh.dispose();
  80826. }
  80827. if (this._debugSphereMesh) {
  80828. this._debugSphereMesh.dispose();
  80829. }
  80830. if (this._debugMaterial) {
  80831. this._debugMaterial.dispose();
  80832. }
  80833. this._impostors.length = 0;
  80834. this._scene = null;
  80835. this._physicsEnginePlugin = null;
  80836. };
  80837. return PhysicsViewer;
  80838. }());
  80839. Debug.SkeletonViewer = /** @class */ (function () {
  80840. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80841. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80842. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80843. this.skeleton = skeleton;
  80844. this.mesh = mesh;
  80845. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80846. this.renderingGroupId = renderingGroupId;
  80847. this.color = BABYLON.Color3.White();
  80848. this._debugLines = new Array();
  80849. this._isEnabled = false;
  80850. this._scene = scene;
  80851. this.update();
  80852. this._renderFunction = this.update.bind(this);
  80853. }
  80854. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80855. get: function () {
  80856. return this._isEnabled;
  80857. },
  80858. set: function (value) {
  80859. if (this._isEnabled === value) {
  80860. return;
  80861. }
  80862. this._isEnabled = value;
  80863. if (value) {
  80864. this._scene.registerBeforeRender(this._renderFunction);
  80865. }
  80866. else {
  80867. this._scene.unregisterBeforeRender(this._renderFunction);
  80868. }
  80869. },
  80870. enumerable: true,
  80871. configurable: true
  80872. });
  80873. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80874. if (x === void 0) { x = 0; }
  80875. if (y === void 0) { y = 0; }
  80876. if (z === void 0) { z = 0; }
  80877. var tmat = BABYLON.Tmp.Matrix[0];
  80878. var parentBone = bone.getParent();
  80879. tmat.copyFrom(bone.getLocalMatrix());
  80880. if (x !== 0 || y !== 0 || z !== 0) {
  80881. var tmat2 = BABYLON.Tmp.Matrix[1];
  80882. BABYLON.Matrix.IdentityToRef(tmat2);
  80883. tmat2.m[12] = x;
  80884. tmat2.m[13] = y;
  80885. tmat2.m[14] = z;
  80886. tmat2.multiplyToRef(tmat, tmat);
  80887. }
  80888. if (parentBone) {
  80889. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80890. }
  80891. tmat.multiplyToRef(meshMat, tmat);
  80892. position.x = tmat.m[12];
  80893. position.y = tmat.m[13];
  80894. position.z = tmat.m[14];
  80895. };
  80896. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80897. var len = bones.length;
  80898. var meshPos = this.mesh.position;
  80899. for (var i = 0; i < len; i++) {
  80900. var bone = bones[i];
  80901. var points = this._debugLines[i];
  80902. if (!points) {
  80903. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80904. this._debugLines[i] = points;
  80905. }
  80906. this._getBonePosition(points[0], bone, meshMat);
  80907. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80908. points[0].subtractInPlace(meshPos);
  80909. points[1].subtractInPlace(meshPos);
  80910. }
  80911. };
  80912. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80913. var len = bones.length;
  80914. var boneNum = 0;
  80915. var meshPos = this.mesh.position;
  80916. for (var i = len - 1; i >= 0; i--) {
  80917. var childBone = bones[i];
  80918. var parentBone = childBone.getParent();
  80919. if (!parentBone) {
  80920. continue;
  80921. }
  80922. var points = this._debugLines[boneNum];
  80923. if (!points) {
  80924. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80925. this._debugLines[boneNum] = points;
  80926. }
  80927. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80928. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80929. points[0].subtractInPlace(meshPos);
  80930. points[1].subtractInPlace(meshPos);
  80931. boneNum++;
  80932. }
  80933. };
  80934. SkeletonViewer.prototype.update = function () {
  80935. if (this.autoUpdateBonesMatrices) {
  80936. this.skeleton.computeAbsoluteTransforms();
  80937. }
  80938. if (this.skeleton.bones[0].length === undefined) {
  80939. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80940. }
  80941. else {
  80942. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80943. }
  80944. if (!this._debugMesh) {
  80945. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80946. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80947. }
  80948. else {
  80949. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80950. }
  80951. this._debugMesh.position.copyFrom(this.mesh.position);
  80952. this._debugMesh.color = this.color;
  80953. };
  80954. SkeletonViewer.prototype.dispose = function () {
  80955. if (this._debugMesh) {
  80956. this.isEnabled = false;
  80957. this._debugMesh.dispose();
  80958. this._debugMesh = null;
  80959. }
  80960. };
  80961. return SkeletonViewer;
  80962. }());
  80963. return Debug;
  80964. }());
  80965. BABYLON.Debug = Debug;
  80966. })(BABYLON || (BABYLON = {}));
  80967. //# sourceMappingURL=babylon.debugModules.js.map
  80968. "use strict";
  80969. var BABYLON;
  80970. (function (BABYLON) {
  80971. var RayHelper = /** @class */ (function () {
  80972. function RayHelper(ray) {
  80973. this.ray = ray;
  80974. }
  80975. RayHelper.CreateAndShow = function (ray, scene, color) {
  80976. var helper = new RayHelper(ray);
  80977. helper.show(scene, color);
  80978. return helper;
  80979. };
  80980. RayHelper.prototype.show = function (scene, color) {
  80981. if (!this._renderFunction && this.ray) {
  80982. var ray = this.ray;
  80983. this._renderFunction = this._render.bind(this);
  80984. this._scene = scene;
  80985. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80986. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80987. if (this._renderFunction) {
  80988. this._scene.registerBeforeRender(this._renderFunction);
  80989. }
  80990. }
  80991. if (color && this._renderLine) {
  80992. this._renderLine.color.copyFrom(color);
  80993. }
  80994. };
  80995. RayHelper.prototype.hide = function () {
  80996. if (this._renderFunction && this._scene) {
  80997. this._scene.unregisterBeforeRender(this._renderFunction);
  80998. this._scene = null;
  80999. this._renderFunction = null;
  81000. if (this._renderLine) {
  81001. this._renderLine.dispose();
  81002. this._renderLine = null;
  81003. }
  81004. this._renderPoints = [];
  81005. }
  81006. };
  81007. RayHelper.prototype._render = function () {
  81008. var ray = this.ray;
  81009. if (!ray) {
  81010. return;
  81011. }
  81012. var point = this._renderPoints[1];
  81013. var len = Math.min(ray.length, 1000000);
  81014. point.copyFrom(ray.direction);
  81015. point.scaleInPlace(len);
  81016. point.addInPlace(ray.origin);
  81017. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  81018. };
  81019. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  81020. this._attachedToMesh = mesh;
  81021. var ray = this.ray;
  81022. if (!ray) {
  81023. return;
  81024. }
  81025. if (!ray.direction) {
  81026. ray.direction = BABYLON.Vector3.Zero();
  81027. }
  81028. if (!ray.origin) {
  81029. ray.origin = BABYLON.Vector3.Zero();
  81030. }
  81031. if (length) {
  81032. ray.length = length;
  81033. }
  81034. if (!meshSpaceOrigin) {
  81035. meshSpaceOrigin = BABYLON.Vector3.Zero();
  81036. }
  81037. if (!meshSpaceDirection) {
  81038. // -1 so that this will work with Mesh.lookAt
  81039. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  81040. }
  81041. if (!this._meshSpaceDirection) {
  81042. this._meshSpaceDirection = meshSpaceDirection.clone();
  81043. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  81044. }
  81045. else {
  81046. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  81047. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  81048. }
  81049. if (!this._updateToMeshFunction) {
  81050. this._updateToMeshFunction = this._updateToMesh.bind(this);
  81051. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  81052. }
  81053. this._updateToMesh();
  81054. };
  81055. RayHelper.prototype.detachFromMesh = function () {
  81056. if (this._attachedToMesh) {
  81057. if (this._updateToMeshFunction) {
  81058. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  81059. }
  81060. this._attachedToMesh = null;
  81061. this._updateToMeshFunction = null;
  81062. }
  81063. };
  81064. RayHelper.prototype._updateToMesh = function () {
  81065. var ray = this.ray;
  81066. if (!this._attachedToMesh || !ray) {
  81067. return;
  81068. }
  81069. if (this._attachedToMesh._isDisposed) {
  81070. this.detachFromMesh();
  81071. return;
  81072. }
  81073. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  81074. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  81075. };
  81076. RayHelper.prototype.dispose = function () {
  81077. this.hide();
  81078. this.detachFromMesh();
  81079. this.ray = null;
  81080. };
  81081. return RayHelper;
  81082. }());
  81083. BABYLON.RayHelper = RayHelper;
  81084. })(BABYLON || (BABYLON = {}));
  81085. //# sourceMappingURL=babylon.rayHelper.js.map
  81086. "use strict";
  81087. var BABYLON;
  81088. (function (BABYLON) {
  81089. // load the inspector using require, if not present in the global namespace.
  81090. var DebugLayer = /** @class */ (function () {
  81091. function DebugLayer(scene) {
  81092. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81093. this._scene = scene;
  81094. // load inspector using require, if it doesn't exist on the global namespace.
  81095. }
  81096. /** Creates the inspector window. */
  81097. DebugLayer.prototype._createInspector = function (config) {
  81098. if (config === void 0) { config = {}; }
  81099. var popup = config.popup || false;
  81100. var initialTab = config.initialTab || 0;
  81101. var parentElement = config.parentElement || null;
  81102. if (!this._inspector) {
  81103. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  81104. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  81105. } // else nothing to do,; instance is already existing
  81106. };
  81107. DebugLayer.prototype.isVisible = function () {
  81108. if (!this._inspector) {
  81109. return false;
  81110. }
  81111. return true;
  81112. };
  81113. DebugLayer.prototype.hide = function () {
  81114. if (this._inspector) {
  81115. try {
  81116. this._inspector.dispose();
  81117. }
  81118. catch (e) {
  81119. // If the inspector has been removed directly from the inspector tool
  81120. }
  81121. this._inspector = null;
  81122. }
  81123. };
  81124. DebugLayer.prototype.show = function (config) {
  81125. if (config === void 0) { config = {}; }
  81126. if (typeof this.BJSINSPECTOR == 'undefined') {
  81127. // Load inspector and add it to the DOM
  81128. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  81129. }
  81130. else {
  81131. // Otherwise creates the inspector
  81132. this._createInspector(config);
  81133. }
  81134. };
  81135. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  81136. return DebugLayer;
  81137. }());
  81138. BABYLON.DebugLayer = DebugLayer;
  81139. })(BABYLON || (BABYLON = {}));
  81140. //# sourceMappingURL=babylon.debugLayer.js.map
  81141. "use strict";
  81142. var BABYLON;
  81143. (function (BABYLON) {
  81144. var BoundingBoxRenderer = /** @class */ (function () {
  81145. function BoundingBoxRenderer(scene) {
  81146. this.frontColor = new BABYLON.Color3(1, 1, 1);
  81147. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  81148. this.showBackLines = true;
  81149. this.renderList = new BABYLON.SmartArray(32);
  81150. this._vertexBuffers = {};
  81151. this._scene = scene;
  81152. }
  81153. BoundingBoxRenderer.prototype._prepareRessources = function () {
  81154. if (this._colorShader) {
  81155. return;
  81156. }
  81157. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  81158. attributes: [BABYLON.VertexBuffer.PositionKind],
  81159. uniforms: ["world", "viewProjection", "color"]
  81160. });
  81161. var engine = this._scene.getEngine();
  81162. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  81163. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  81164. this._createIndexBuffer();
  81165. };
  81166. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  81167. var engine = this._scene.getEngine();
  81168. 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]);
  81169. };
  81170. BoundingBoxRenderer.prototype._rebuild = function () {
  81171. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81172. if (vb) {
  81173. vb._rebuild();
  81174. }
  81175. this._createIndexBuffer();
  81176. };
  81177. BoundingBoxRenderer.prototype.reset = function () {
  81178. this.renderList.reset();
  81179. };
  81180. BoundingBoxRenderer.prototype.render = function () {
  81181. if (this.renderList.length === 0) {
  81182. return;
  81183. }
  81184. this._prepareRessources();
  81185. if (!this._colorShader.isReady()) {
  81186. return;
  81187. }
  81188. var engine = this._scene.getEngine();
  81189. engine.setDepthWrite(false);
  81190. this._colorShader._preBind();
  81191. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  81192. var boundingBox = this.renderList.data[boundingBoxIndex];
  81193. var min = boundingBox.minimum;
  81194. var max = boundingBox.maximum;
  81195. var diff = max.subtract(min);
  81196. var median = min.add(diff.scale(0.5));
  81197. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81198. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81199. .multiply(boundingBox.getWorldMatrix());
  81200. // VBOs
  81201. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81202. if (this.showBackLines) {
  81203. // Back
  81204. engine.setDepthFunctionToGreaterOrEqual();
  81205. this._scene.resetCachedMaterial();
  81206. this._colorShader.setColor4("color", this.backColor.toColor4());
  81207. this._colorShader.bind(worldMatrix);
  81208. // Draw order
  81209. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81210. }
  81211. // Front
  81212. engine.setDepthFunctionToLess();
  81213. this._scene.resetCachedMaterial();
  81214. this._colorShader.setColor4("color", this.frontColor.toColor4());
  81215. this._colorShader.bind(worldMatrix);
  81216. // Draw order
  81217. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81218. }
  81219. this._colorShader.unbind();
  81220. engine.setDepthFunctionToLessOrEqual();
  81221. engine.setDepthWrite(true);
  81222. };
  81223. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  81224. this._prepareRessources();
  81225. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  81226. return;
  81227. }
  81228. var engine = this._scene.getEngine();
  81229. engine.setDepthWrite(false);
  81230. engine.setColorWrite(false);
  81231. this._colorShader._preBind();
  81232. var boundingBox = mesh._boundingInfo.boundingBox;
  81233. var min = boundingBox.minimum;
  81234. var max = boundingBox.maximum;
  81235. var diff = max.subtract(min);
  81236. var median = min.add(diff.scale(0.5));
  81237. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  81238. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  81239. .multiply(boundingBox.getWorldMatrix());
  81240. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  81241. engine.setDepthFunctionToLess();
  81242. this._scene.resetCachedMaterial();
  81243. this._colorShader.bind(worldMatrix);
  81244. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  81245. this._colorShader.unbind();
  81246. engine.setDepthFunctionToLessOrEqual();
  81247. engine.setDepthWrite(true);
  81248. engine.setColorWrite(true);
  81249. };
  81250. BoundingBoxRenderer.prototype.dispose = function () {
  81251. if (!this._colorShader) {
  81252. return;
  81253. }
  81254. this.renderList.dispose();
  81255. this._colorShader.dispose();
  81256. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81257. if (buffer) {
  81258. buffer.dispose();
  81259. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81260. }
  81261. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81262. };
  81263. return BoundingBoxRenderer;
  81264. }());
  81265. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  81266. })(BABYLON || (BABYLON = {}));
  81267. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  81268. "use strict";
  81269. var BABYLON;
  81270. (function (BABYLON) {
  81271. var MorphTarget = /** @class */ (function () {
  81272. function MorphTarget(name, influence) {
  81273. if (influence === void 0) { influence = 0; }
  81274. this.name = name;
  81275. this.animations = new Array();
  81276. this._positions = null;
  81277. this._normals = null;
  81278. this._tangents = null;
  81279. this.onInfluenceChanged = new BABYLON.Observable();
  81280. this.influence = influence;
  81281. }
  81282. Object.defineProperty(MorphTarget.prototype, "influence", {
  81283. get: function () {
  81284. return this._influence;
  81285. },
  81286. set: function (influence) {
  81287. if (this._influence === influence) {
  81288. return;
  81289. }
  81290. var previous = this._influence;
  81291. this._influence = influence;
  81292. if (this.onInfluenceChanged.hasObservers) {
  81293. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  81294. }
  81295. },
  81296. enumerable: true,
  81297. configurable: true
  81298. });
  81299. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  81300. get: function () {
  81301. return !!this._positions;
  81302. },
  81303. enumerable: true,
  81304. configurable: true
  81305. });
  81306. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  81307. get: function () {
  81308. return !!this._normals;
  81309. },
  81310. enumerable: true,
  81311. configurable: true
  81312. });
  81313. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  81314. get: function () {
  81315. return !!this._tangents;
  81316. },
  81317. enumerable: true,
  81318. configurable: true
  81319. });
  81320. MorphTarget.prototype.setPositions = function (data) {
  81321. this._positions = data;
  81322. };
  81323. MorphTarget.prototype.getPositions = function () {
  81324. return this._positions;
  81325. };
  81326. MorphTarget.prototype.setNormals = function (data) {
  81327. this._normals = data;
  81328. };
  81329. MorphTarget.prototype.getNormals = function () {
  81330. return this._normals;
  81331. };
  81332. MorphTarget.prototype.setTangents = function (data) {
  81333. this._tangents = data;
  81334. };
  81335. MorphTarget.prototype.getTangents = function () {
  81336. return this._tangents;
  81337. };
  81338. /**
  81339. * Serializes the current target into a Serialization object.
  81340. * Returns the serialized object.
  81341. */
  81342. MorphTarget.prototype.serialize = function () {
  81343. var serializationObject = {};
  81344. serializationObject.name = this.name;
  81345. serializationObject.influence = this.influence;
  81346. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  81347. if (this.hasNormals) {
  81348. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  81349. }
  81350. if (this.hasTangents) {
  81351. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  81352. }
  81353. // Animations
  81354. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  81355. return serializationObject;
  81356. };
  81357. // Statics
  81358. MorphTarget.Parse = function (serializationObject) {
  81359. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  81360. result.setPositions(serializationObject.positions);
  81361. if (serializationObject.normals) {
  81362. result.setNormals(serializationObject.normals);
  81363. }
  81364. if (serializationObject.tangents) {
  81365. result.setTangents(serializationObject.tangents);
  81366. }
  81367. // Animations
  81368. if (serializationObject.animations) {
  81369. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  81370. var parsedAnimation = serializationObject.animations[animationIndex];
  81371. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  81372. }
  81373. }
  81374. return result;
  81375. };
  81376. MorphTarget.FromMesh = function (mesh, name, influence) {
  81377. if (!name) {
  81378. name = mesh.name;
  81379. }
  81380. var result = new MorphTarget(name, influence);
  81381. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  81382. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  81383. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  81384. }
  81385. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  81386. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  81387. }
  81388. return result;
  81389. };
  81390. return MorphTarget;
  81391. }());
  81392. BABYLON.MorphTarget = MorphTarget;
  81393. })(BABYLON || (BABYLON = {}));
  81394. //# sourceMappingURL=babylon.morphTarget.js.map
  81395. "use strict";
  81396. var BABYLON;
  81397. (function (BABYLON) {
  81398. var MorphTargetManager = /** @class */ (function () {
  81399. function MorphTargetManager(scene) {
  81400. if (scene === void 0) { scene = null; }
  81401. this._targets = new Array();
  81402. this._targetObservable = new Array();
  81403. this._activeTargets = new BABYLON.SmartArray(16);
  81404. this._supportsNormals = false;
  81405. this._supportsTangents = false;
  81406. this._vertexCount = 0;
  81407. this._uniqueId = 0;
  81408. this._tempInfluences = new Array();
  81409. if (!scene) {
  81410. scene = BABYLON.Engine.LastCreatedScene;
  81411. }
  81412. this._scene = scene;
  81413. if (this._scene) {
  81414. this._scene.morphTargetManagers.push(this);
  81415. this._uniqueId = this._scene.getUniqueId();
  81416. }
  81417. }
  81418. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  81419. get: function () {
  81420. return this._uniqueId;
  81421. },
  81422. enumerable: true,
  81423. configurable: true
  81424. });
  81425. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  81426. get: function () {
  81427. return this._vertexCount;
  81428. },
  81429. enumerable: true,
  81430. configurable: true
  81431. });
  81432. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  81433. get: function () {
  81434. return this._supportsNormals;
  81435. },
  81436. enumerable: true,
  81437. configurable: true
  81438. });
  81439. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  81440. get: function () {
  81441. return this._supportsTangents;
  81442. },
  81443. enumerable: true,
  81444. configurable: true
  81445. });
  81446. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  81447. get: function () {
  81448. return this._targets.length;
  81449. },
  81450. enumerable: true,
  81451. configurable: true
  81452. });
  81453. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  81454. get: function () {
  81455. return this._activeTargets.length;
  81456. },
  81457. enumerable: true,
  81458. configurable: true
  81459. });
  81460. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  81461. get: function () {
  81462. return this._influences;
  81463. },
  81464. enumerable: true,
  81465. configurable: true
  81466. });
  81467. MorphTargetManager.prototype.getActiveTarget = function (index) {
  81468. return this._activeTargets.data[index];
  81469. };
  81470. MorphTargetManager.prototype.getTarget = function (index) {
  81471. return this._targets[index];
  81472. };
  81473. MorphTargetManager.prototype.addTarget = function (target) {
  81474. var _this = this;
  81475. this._targets.push(target);
  81476. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  81477. _this._syncActiveTargets(needUpdate);
  81478. }));
  81479. this._syncActiveTargets(true);
  81480. };
  81481. MorphTargetManager.prototype.removeTarget = function (target) {
  81482. var index = this._targets.indexOf(target);
  81483. if (index >= 0) {
  81484. this._targets.splice(index, 1);
  81485. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  81486. this._syncActiveTargets(true);
  81487. }
  81488. };
  81489. /**
  81490. * Serializes the current manager into a Serialization object.
  81491. * Returns the serialized object.
  81492. */
  81493. MorphTargetManager.prototype.serialize = function () {
  81494. var serializationObject = {};
  81495. serializationObject.id = this.uniqueId;
  81496. serializationObject.targets = [];
  81497. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81498. var target = _a[_i];
  81499. serializationObject.targets.push(target.serialize());
  81500. }
  81501. return serializationObject;
  81502. };
  81503. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  81504. var influenceCount = 0;
  81505. this._activeTargets.reset();
  81506. this._supportsNormals = true;
  81507. this._supportsTangents = true;
  81508. this._vertexCount = 0;
  81509. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  81510. var target = _a[_i];
  81511. this._activeTargets.push(target);
  81512. this._tempInfluences[influenceCount++] = target.influence;
  81513. var positions = target.getPositions();
  81514. if (positions) {
  81515. this._supportsNormals = this._supportsNormals && target.hasNormals;
  81516. this._supportsTangents = this._supportsTangents && target.hasTangents;
  81517. var vertexCount = positions.length / 3;
  81518. if (this._vertexCount === 0) {
  81519. this._vertexCount = vertexCount;
  81520. }
  81521. else if (this._vertexCount !== vertexCount) {
  81522. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  81523. return;
  81524. }
  81525. }
  81526. }
  81527. if (!this._influences || this._influences.length !== influenceCount) {
  81528. this._influences = new Float32Array(influenceCount);
  81529. }
  81530. for (var index = 0; index < influenceCount; index++) {
  81531. this._influences[index] = this._tempInfluences[index];
  81532. }
  81533. if (needUpdate && this._scene) {
  81534. // Flag meshes as dirty to resync with the active targets
  81535. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  81536. var mesh = _c[_b];
  81537. if (mesh.morphTargetManager === this) {
  81538. mesh._syncGeometryWithMorphTargetManager();
  81539. }
  81540. }
  81541. }
  81542. };
  81543. // Statics
  81544. MorphTargetManager.Parse = function (serializationObject, scene) {
  81545. var result = new MorphTargetManager(scene);
  81546. result._uniqueId = serializationObject.id;
  81547. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81548. var targetData = _a[_i];
  81549. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81550. }
  81551. return result;
  81552. };
  81553. return MorphTargetManager;
  81554. }());
  81555. BABYLON.MorphTargetManager = MorphTargetManager;
  81556. })(BABYLON || (BABYLON = {}));
  81557. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81558. "use strict";
  81559. var BABYLON;
  81560. (function (BABYLON) {
  81561. var Octree = /** @class */ (function () {
  81562. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81563. if (maxDepth === void 0) { maxDepth = 2; }
  81564. this.maxDepth = maxDepth;
  81565. this.dynamicContent = new Array();
  81566. this._maxBlockCapacity = maxBlockCapacity || 64;
  81567. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81568. this._creationFunc = creationFunc;
  81569. }
  81570. // Methods
  81571. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81572. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81573. };
  81574. Octree.prototype.addMesh = function (entry) {
  81575. for (var index = 0; index < this.blocks.length; index++) {
  81576. var block = this.blocks[index];
  81577. block.addEntry(entry);
  81578. }
  81579. };
  81580. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81581. this._selectionContent.reset();
  81582. for (var index = 0; index < this.blocks.length; index++) {
  81583. var block = this.blocks[index];
  81584. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81585. }
  81586. if (allowDuplicate) {
  81587. this._selectionContent.concat(this.dynamicContent);
  81588. }
  81589. else {
  81590. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81591. }
  81592. return this._selectionContent;
  81593. };
  81594. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81595. this._selectionContent.reset();
  81596. for (var index = 0; index < this.blocks.length; index++) {
  81597. var block = this.blocks[index];
  81598. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81599. }
  81600. if (allowDuplicate) {
  81601. this._selectionContent.concat(this.dynamicContent);
  81602. }
  81603. else {
  81604. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81605. }
  81606. return this._selectionContent;
  81607. };
  81608. Octree.prototype.intersectsRay = function (ray) {
  81609. this._selectionContent.reset();
  81610. for (var index = 0; index < this.blocks.length; index++) {
  81611. var block = this.blocks[index];
  81612. block.intersectsRay(ray, this._selectionContent);
  81613. }
  81614. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81615. return this._selectionContent;
  81616. };
  81617. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81618. target.blocks = new Array();
  81619. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81620. // Segmenting space
  81621. for (var x = 0; x < 2; x++) {
  81622. for (var y = 0; y < 2; y++) {
  81623. for (var z = 0; z < 2; z++) {
  81624. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81625. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81626. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81627. block.addEntries(entries);
  81628. target.blocks.push(block);
  81629. }
  81630. }
  81631. }
  81632. };
  81633. Octree.CreationFuncForMeshes = function (entry, block) {
  81634. var boundingInfo = entry.getBoundingInfo();
  81635. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81636. block.entries.push(entry);
  81637. }
  81638. };
  81639. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81640. var boundingInfo = entry.getBoundingInfo();
  81641. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81642. block.entries.push(entry);
  81643. }
  81644. };
  81645. return Octree;
  81646. }());
  81647. BABYLON.Octree = Octree;
  81648. })(BABYLON || (BABYLON = {}));
  81649. //# sourceMappingURL=babylon.octree.js.map
  81650. "use strict";
  81651. var BABYLON;
  81652. (function (BABYLON) {
  81653. var OctreeBlock = /** @class */ (function () {
  81654. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81655. this.entries = new Array();
  81656. this._boundingVectors = new Array();
  81657. this._capacity = capacity;
  81658. this._depth = depth;
  81659. this._maxDepth = maxDepth;
  81660. this._creationFunc = creationFunc;
  81661. this._minPoint = minPoint;
  81662. this._maxPoint = maxPoint;
  81663. this._boundingVectors.push(minPoint.clone());
  81664. this._boundingVectors.push(maxPoint.clone());
  81665. this._boundingVectors.push(minPoint.clone());
  81666. this._boundingVectors[2].x = maxPoint.x;
  81667. this._boundingVectors.push(minPoint.clone());
  81668. this._boundingVectors[3].y = maxPoint.y;
  81669. this._boundingVectors.push(minPoint.clone());
  81670. this._boundingVectors[4].z = maxPoint.z;
  81671. this._boundingVectors.push(maxPoint.clone());
  81672. this._boundingVectors[5].z = minPoint.z;
  81673. this._boundingVectors.push(maxPoint.clone());
  81674. this._boundingVectors[6].x = minPoint.x;
  81675. this._boundingVectors.push(maxPoint.clone());
  81676. this._boundingVectors[7].y = minPoint.y;
  81677. }
  81678. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81679. // Property
  81680. get: function () {
  81681. return this._capacity;
  81682. },
  81683. enumerable: true,
  81684. configurable: true
  81685. });
  81686. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81687. get: function () {
  81688. return this._minPoint;
  81689. },
  81690. enumerable: true,
  81691. configurable: true
  81692. });
  81693. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81694. get: function () {
  81695. return this._maxPoint;
  81696. },
  81697. enumerable: true,
  81698. configurable: true
  81699. });
  81700. // Methods
  81701. OctreeBlock.prototype.addEntry = function (entry) {
  81702. if (this.blocks) {
  81703. for (var index = 0; index < this.blocks.length; index++) {
  81704. var block = this.blocks[index];
  81705. block.addEntry(entry);
  81706. }
  81707. return;
  81708. }
  81709. this._creationFunc(entry, this);
  81710. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81711. this.createInnerBlocks();
  81712. }
  81713. };
  81714. OctreeBlock.prototype.addEntries = function (entries) {
  81715. for (var index = 0; index < entries.length; index++) {
  81716. var mesh = entries[index];
  81717. this.addEntry(mesh);
  81718. }
  81719. };
  81720. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81721. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81722. if (this.blocks) {
  81723. for (var index = 0; index < this.blocks.length; index++) {
  81724. var block = this.blocks[index];
  81725. block.select(frustumPlanes, selection, allowDuplicate);
  81726. }
  81727. return;
  81728. }
  81729. if (allowDuplicate) {
  81730. selection.concat(this.entries);
  81731. }
  81732. else {
  81733. selection.concatWithNoDuplicate(this.entries);
  81734. }
  81735. }
  81736. };
  81737. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81738. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81739. if (this.blocks) {
  81740. for (var index = 0; index < this.blocks.length; index++) {
  81741. var block = this.blocks[index];
  81742. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81743. }
  81744. return;
  81745. }
  81746. if (allowDuplicate) {
  81747. selection.concat(this.entries);
  81748. }
  81749. else {
  81750. selection.concatWithNoDuplicate(this.entries);
  81751. }
  81752. }
  81753. };
  81754. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81755. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81756. if (this.blocks) {
  81757. for (var index = 0; index < this.blocks.length; index++) {
  81758. var block = this.blocks[index];
  81759. block.intersectsRay(ray, selection);
  81760. }
  81761. return;
  81762. }
  81763. selection.concatWithNoDuplicate(this.entries);
  81764. }
  81765. };
  81766. OctreeBlock.prototype.createInnerBlocks = function () {
  81767. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81768. };
  81769. return OctreeBlock;
  81770. }());
  81771. BABYLON.OctreeBlock = OctreeBlock;
  81772. })(BABYLON || (BABYLON = {}));
  81773. //# sourceMappingURL=babylon.octreeBlock.js.map
  81774. "use strict";
  81775. var BABYLON;
  81776. (function (BABYLON) {
  81777. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81778. __extends(VRDistortionCorrectionPostProcess, _super);
  81779. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81780. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81781. 'LensCenter',
  81782. 'Scale',
  81783. 'ScaleIn',
  81784. 'HmdWarpParam'
  81785. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81786. _this._isRightEye = isRightEye;
  81787. _this._distortionFactors = vrMetrics.distortionK;
  81788. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81789. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81790. _this.adaptScaleToCurrentViewport = true;
  81791. _this.onSizeChangedObservable.add(function () {
  81792. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81793. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81794. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81795. });
  81796. _this.onApplyObservable.add(function (effect) {
  81797. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81798. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81799. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81800. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81801. });
  81802. return _this;
  81803. }
  81804. return VRDistortionCorrectionPostProcess;
  81805. }(BABYLON.PostProcess));
  81806. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81807. })(BABYLON || (BABYLON = {}));
  81808. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81809. "use strict";
  81810. var BABYLON;
  81811. (function (BABYLON) {
  81812. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81813. __extends(AnaglyphPostProcess, _super);
  81814. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81815. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81816. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81817. _this.onApplyObservable.add(function (effect) {
  81818. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81819. });
  81820. return _this;
  81821. }
  81822. return AnaglyphPostProcess;
  81823. }(BABYLON.PostProcess));
  81824. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81825. })(BABYLON || (BABYLON = {}));
  81826. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81827. "use strict";
  81828. var BABYLON;
  81829. (function (BABYLON) {
  81830. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81831. __extends(StereoscopicInterlacePostProcess, _super);
  81832. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81833. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81834. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81835. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81836. _this.onSizeChangedObservable.add(function () {
  81837. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81838. });
  81839. _this.onApplyObservable.add(function (effect) {
  81840. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81841. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81842. });
  81843. return _this;
  81844. }
  81845. return StereoscopicInterlacePostProcess;
  81846. }(BABYLON.PostProcess));
  81847. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81848. })(BABYLON || (BABYLON = {}));
  81849. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81850. "use strict";
  81851. var BABYLON;
  81852. (function (BABYLON) {
  81853. /**
  81854. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81855. * Screen rotation is taken into account.
  81856. */
  81857. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81858. function FreeCameraDeviceOrientationInput() {
  81859. var _this = this;
  81860. this._screenOrientationAngle = 0;
  81861. this._screenQuaternion = new BABYLON.Quaternion();
  81862. this._alpha = 0;
  81863. this._beta = 0;
  81864. this._gamma = 0;
  81865. this._orientationChanged = function () {
  81866. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81867. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81868. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81869. };
  81870. this._deviceOrientation = function (evt) {
  81871. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81872. _this._beta = evt.beta !== null ? evt.beta : 0;
  81873. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81874. };
  81875. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81876. this._orientationChanged();
  81877. }
  81878. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81879. get: function () {
  81880. return this._camera;
  81881. },
  81882. set: function (camera) {
  81883. this._camera = camera;
  81884. if (this._camera != null && !this._camera.rotationQuaternion) {
  81885. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81886. }
  81887. },
  81888. enumerable: true,
  81889. configurable: true
  81890. });
  81891. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81892. window.addEventListener("orientationchange", this._orientationChanged);
  81893. window.addEventListener("deviceorientation", this._deviceOrientation);
  81894. //In certain cases, the attach control is called AFTER orientation was changed,
  81895. //So this is needed.
  81896. this._orientationChanged();
  81897. };
  81898. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81899. window.removeEventListener("orientationchange", this._orientationChanged);
  81900. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81901. };
  81902. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81903. //if no device orientation provided, don't update the rotation.
  81904. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81905. if (!this._alpha)
  81906. return;
  81907. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81908. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81909. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81910. //Mirror on XY Plane
  81911. this._camera.rotationQuaternion.z *= -1;
  81912. this._camera.rotationQuaternion.w *= -1;
  81913. };
  81914. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81915. return "FreeCameraDeviceOrientationInput";
  81916. };
  81917. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81918. return "deviceOrientation";
  81919. };
  81920. return FreeCameraDeviceOrientationInput;
  81921. }());
  81922. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81923. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81924. })(BABYLON || (BABYLON = {}));
  81925. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81926. "use strict";
  81927. var BABYLON;
  81928. (function (BABYLON) {
  81929. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81930. function ArcRotateCameraVRDeviceOrientationInput() {
  81931. this.alphaCorrection = 1;
  81932. this.betaCorrection = 1;
  81933. this.gammaCorrection = 1;
  81934. this._alpha = 0;
  81935. this._gamma = 0;
  81936. this._dirty = false;
  81937. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81938. }
  81939. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81940. this.camera.attachControl(element, noPreventDefault);
  81941. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81942. };
  81943. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81944. if (evt.alpha !== null) {
  81945. this._alpha = +evt.alpha | 0;
  81946. }
  81947. if (evt.gamma !== null) {
  81948. this._gamma = +evt.gamma | 0;
  81949. }
  81950. this._dirty = true;
  81951. };
  81952. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81953. if (this._dirty) {
  81954. this._dirty = false;
  81955. if (this._gamma < 0) {
  81956. this._gamma = 180 + this._gamma;
  81957. }
  81958. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81959. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81960. }
  81961. };
  81962. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81963. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81964. };
  81965. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81966. return "ArcRotateCameraVRDeviceOrientationInput";
  81967. };
  81968. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81969. return "VRDeviceOrientation";
  81970. };
  81971. return ArcRotateCameraVRDeviceOrientationInput;
  81972. }());
  81973. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81974. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81975. })(BABYLON || (BABYLON = {}));
  81976. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81977. "use strict";
  81978. var BABYLON;
  81979. (function (BABYLON) {
  81980. var VRCameraMetrics = /** @class */ (function () {
  81981. function VRCameraMetrics() {
  81982. this.compensateDistortion = true;
  81983. }
  81984. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81985. get: function () {
  81986. return this.hResolution / (2 * this.vResolution);
  81987. },
  81988. enumerable: true,
  81989. configurable: true
  81990. });
  81991. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81992. get: function () {
  81993. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81994. },
  81995. enumerable: true,
  81996. configurable: true
  81997. });
  81998. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81999. get: function () {
  82000. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82001. var h = (4 * meters) / this.hScreenSize;
  82002. return BABYLON.Matrix.Translation(h, 0, 0);
  82003. },
  82004. enumerable: true,
  82005. configurable: true
  82006. });
  82007. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  82008. get: function () {
  82009. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  82010. var h = (4 * meters) / this.hScreenSize;
  82011. return BABYLON.Matrix.Translation(-h, 0, 0);
  82012. },
  82013. enumerable: true,
  82014. configurable: true
  82015. });
  82016. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  82017. get: function () {
  82018. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  82019. },
  82020. enumerable: true,
  82021. configurable: true
  82022. });
  82023. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  82024. get: function () {
  82025. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  82026. },
  82027. enumerable: true,
  82028. configurable: true
  82029. });
  82030. VRCameraMetrics.GetDefault = function () {
  82031. var result = new VRCameraMetrics();
  82032. result.hResolution = 1280;
  82033. result.vResolution = 800;
  82034. result.hScreenSize = 0.149759993;
  82035. result.vScreenSize = 0.0935999975;
  82036. result.vScreenCenter = 0.0467999987;
  82037. result.eyeToScreenDistance = 0.0410000011;
  82038. result.lensSeparationDistance = 0.0635000020;
  82039. result.interpupillaryDistance = 0.0640000030;
  82040. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  82041. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  82042. result.postProcessScaleFactor = 1.714605507808412;
  82043. result.lensCenterOffset = 0.151976421;
  82044. return result;
  82045. };
  82046. return VRCameraMetrics;
  82047. }());
  82048. BABYLON.VRCameraMetrics = VRCameraMetrics;
  82049. })(BABYLON || (BABYLON = {}));
  82050. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  82051. "use strict";
  82052. var BABYLON;
  82053. (function (BABYLON) {
  82054. /**
  82055. * This represents a WebVR camera.
  82056. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  82057. * @example http://doc.babylonjs.com/how_to/webvr_camera
  82058. */
  82059. var WebVRFreeCamera = /** @class */ (function (_super) {
  82060. __extends(WebVRFreeCamera, _super);
  82061. /**
  82062. * Instantiates a WebVRFreeCamera.
  82063. * @param name The name of the WebVRFreeCamera
  82064. * @param position The starting anchor position for the camera
  82065. * @param scene The scene the camera belongs to
  82066. * @param webVROptions a set of customizable options for the webVRCamera
  82067. */
  82068. function WebVRFreeCamera(name, position, scene, webVROptions) {
  82069. if (webVROptions === void 0) { webVROptions = {}; }
  82070. var _this = _super.call(this, name, position, scene) || this;
  82071. _this.webVROptions = webVROptions;
  82072. /**
  82073. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  82074. */
  82075. _this._vrDevice = null;
  82076. /**
  82077. * The rawPose of the vrDevice.
  82078. */
  82079. _this.rawPose = null;
  82080. _this._specsVersion = "1.1";
  82081. _this._attached = false;
  82082. _this._descendants = [];
  82083. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  82084. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  82085. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  82086. _this._standingMatrix = null;
  82087. /**
  82088. * Represents device position in babylon space.
  82089. */
  82090. _this.devicePosition = BABYLON.Vector3.Zero();
  82091. /**
  82092. * Represents device rotation in babylon space.
  82093. */
  82094. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  82095. /**
  82096. * The scale of the device to be used when translating from device space to babylon space.
  82097. */
  82098. _this.deviceScaleFactor = 1;
  82099. _this._deviceToWorld = BABYLON.Matrix.Identity();
  82100. _this._worldToDevice = BABYLON.Matrix.Identity();
  82101. /**
  82102. * References to the webVR controllers for the vrDevice.
  82103. */
  82104. _this.controllers = [];
  82105. /**
  82106. * Emits an event when a controller is attached.
  82107. */
  82108. _this.onControllersAttachedObservable = new BABYLON.Observable();
  82109. /**
  82110. * Emits an event when a controller's mesh has been loaded;
  82111. */
  82112. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82113. /**
  82114. * If the rig cameras be used as parent instead of this camera.
  82115. */
  82116. _this.rigParenting = true;
  82117. _this._defaultHeight = undefined;
  82118. _this._workingVector = BABYLON.Vector3.Zero();
  82119. _this._oneVector = BABYLON.Vector3.One();
  82120. _this._workingMatrix = BABYLON.Matrix.Identity();
  82121. _this._cache.position = BABYLON.Vector3.Zero();
  82122. if (webVROptions.defaultHeight) {
  82123. _this._defaultHeight = webVROptions.defaultHeight;
  82124. _this.position.y = _this._defaultHeight;
  82125. }
  82126. _this.minZ = 0.1;
  82127. //legacy support - the compensation boolean was removed.
  82128. if (arguments.length === 5) {
  82129. _this.webVROptions = arguments[4];
  82130. }
  82131. // default webVR options
  82132. if (_this.webVROptions.trackPosition == undefined) {
  82133. _this.webVROptions.trackPosition = true;
  82134. }
  82135. if (_this.webVROptions.controllerMeshes == undefined) {
  82136. _this.webVROptions.controllerMeshes = true;
  82137. }
  82138. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  82139. _this.webVROptions.defaultLightingOnControllers = true;
  82140. }
  82141. _this.rotationQuaternion = new BABYLON.Quaternion();
  82142. if (_this.webVROptions && _this.webVROptions.positionScale) {
  82143. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  82144. }
  82145. //enable VR
  82146. var engine = _this.getEngine();
  82147. _this._onVREnabled = function (success) { if (success) {
  82148. _this.initControllers();
  82149. } };
  82150. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  82151. engine.initWebVR().add(function (event) {
  82152. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  82153. return;
  82154. }
  82155. _this._vrDevice = event.vrDisplay;
  82156. //reset the rig parameters.
  82157. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  82158. if (_this._attached) {
  82159. _this.getEngine().enableVR();
  82160. }
  82161. });
  82162. if (typeof (VRFrameData) !== "undefined")
  82163. _this._frameData = new VRFrameData();
  82164. /**
  82165. * The idea behind the following lines:
  82166. * objects that have the camera as parent should actually have the rig cameras as a parent.
  82167. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  82168. * the second will not show it correctly.
  82169. *
  82170. * To solve this - each object that has the camera as parent will be added to a protected array.
  82171. * When the rig camera renders, it will take this array and set all of those to be its children.
  82172. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  82173. * Amazing!
  82174. */
  82175. scene.onBeforeCameraRenderObservable.add(function (camera) {
  82176. if (camera.parent === _this && _this.rigParenting) {
  82177. _this._descendants = _this.getDescendants(true, function (n) {
  82178. // don't take the cameras or the controllers!
  82179. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  82180. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  82181. return !isController && !isRigCamera;
  82182. });
  82183. _this._descendants.forEach(function (node) {
  82184. node.parent = camera;
  82185. });
  82186. }
  82187. });
  82188. scene.onAfterCameraRenderObservable.add(function (camera) {
  82189. if (camera.parent === _this && _this.rigParenting) {
  82190. _this._descendants.forEach(function (node) {
  82191. node.parent = _this;
  82192. });
  82193. }
  82194. });
  82195. return _this;
  82196. }
  82197. /**
  82198. * Gets the device distance from the ground in meters.
  82199. * @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.
  82200. */
  82201. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  82202. if (this._standingMatrix) {
  82203. // Add standing matrix offset to get real offset from ground in room
  82204. this._standingMatrix.getTranslationToRef(this._workingVector);
  82205. return this._deviceRoomPosition.y + this._workingVector.y;
  82206. }
  82207. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  82208. return this._defaultHeight || 0;
  82209. };
  82210. /**
  82211. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82212. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  82213. */
  82214. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  82215. var _this = this;
  82216. if (callback === void 0) { callback = function (bool) { }; }
  82217. // Use standing matrix if available
  82218. this.getEngine().initWebVRAsync().then(function (result) {
  82219. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  82220. callback(false);
  82221. }
  82222. else {
  82223. _this._standingMatrix = new BABYLON.Matrix();
  82224. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  82225. if (!_this.getScene().useRightHandedSystem) {
  82226. [2, 6, 8, 9, 14].forEach(function (num) {
  82227. if (_this._standingMatrix) {
  82228. _this._standingMatrix.m[num] *= -1;
  82229. }
  82230. });
  82231. }
  82232. callback(true);
  82233. }
  82234. });
  82235. };
  82236. /**
  82237. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  82238. * @returns A promise with a boolean set to if the standing matrix is supported.
  82239. */
  82240. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  82241. var _this = this;
  82242. return new Promise(function (res, rej) {
  82243. _this.useStandingMatrix(function (supported) {
  82244. res(supported);
  82245. });
  82246. });
  82247. };
  82248. /**
  82249. * Disposes the camera
  82250. */
  82251. WebVRFreeCamera.prototype.dispose = function () {
  82252. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  82253. _super.prototype.dispose.call(this);
  82254. };
  82255. /**
  82256. * Gets a vrController by name.
  82257. * @param name The name of the controller to retreive
  82258. * @returns the controller matching the name specified or null if not found
  82259. */
  82260. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  82261. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  82262. var gp = _a[_i];
  82263. if (gp.hand === name) {
  82264. return gp;
  82265. }
  82266. }
  82267. return null;
  82268. };
  82269. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  82270. /**
  82271. * The controller corrisponding to the users left hand.
  82272. */
  82273. get: function () {
  82274. if (!this._leftController) {
  82275. this._leftController = this.getControllerByName("left");
  82276. }
  82277. return this._leftController;
  82278. },
  82279. enumerable: true,
  82280. configurable: true
  82281. });
  82282. ;
  82283. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  82284. /**
  82285. * The controller corrisponding to the users right hand.
  82286. */
  82287. get: function () {
  82288. if (!this._rightController) {
  82289. this._rightController = this.getControllerByName("right");
  82290. }
  82291. return this._rightController;
  82292. },
  82293. enumerable: true,
  82294. configurable: true
  82295. });
  82296. ;
  82297. /**
  82298. * Casts a ray forward from the vrCamera's gaze.
  82299. * @param length Length of the ray (default: 100)
  82300. * @returns the ray corrisponding to the gaze
  82301. */
  82302. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  82303. if (length === void 0) { length = 100; }
  82304. if (this.leftCamera) {
  82305. // Use left eye to avoid computation to compute center on every call
  82306. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  82307. }
  82308. else {
  82309. return _super.prototype.getForwardRay.call(this, length);
  82310. }
  82311. };
  82312. /**
  82313. * Updates the camera based on device's frame data
  82314. */
  82315. WebVRFreeCamera.prototype._checkInputs = function () {
  82316. if (this._vrDevice && this._vrDevice.isPresenting) {
  82317. this._vrDevice.getFrameData(this._frameData);
  82318. this.updateFromDevice(this._frameData.pose);
  82319. }
  82320. _super.prototype._checkInputs.call(this);
  82321. };
  82322. /**
  82323. * Updates the poseControlled values based on the input device pose.
  82324. * @param poseData Pose coming from the device
  82325. */
  82326. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  82327. if (poseData && poseData.orientation) {
  82328. this.rawPose = poseData;
  82329. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  82330. if (this.getScene().useRightHandedSystem) {
  82331. this._deviceRoomRotationQuaternion.z *= -1;
  82332. this._deviceRoomRotationQuaternion.w *= -1;
  82333. }
  82334. if (this.webVROptions.trackPosition && this.rawPose.position) {
  82335. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  82336. if (this.getScene().useRightHandedSystem) {
  82337. this._deviceRoomPosition.z *= -1;
  82338. }
  82339. }
  82340. }
  82341. };
  82342. /**
  82343. * WebVR's attach control will start broadcasting frames to the device.
  82344. * Note that in certain browsers (chrome for example) this function must be called
  82345. * within a user-interaction callback. Example:
  82346. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  82347. *
  82348. * @param element html element to attach the vrDevice to
  82349. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  82350. */
  82351. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  82352. _super.prototype.attachControl.call(this, element, noPreventDefault);
  82353. this._attached = true;
  82354. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  82355. if (this._vrDevice) {
  82356. this.getEngine().enableVR();
  82357. }
  82358. };
  82359. /**
  82360. * Detaches the camera from the html element and disables VR
  82361. *
  82362. * @param element html element to detach from
  82363. */
  82364. WebVRFreeCamera.prototype.detachControl = function (element) {
  82365. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  82366. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  82367. _super.prototype.detachControl.call(this, element);
  82368. this._attached = false;
  82369. this.getEngine().disableVR();
  82370. };
  82371. /**
  82372. * @returns the name of this class
  82373. */
  82374. WebVRFreeCamera.prototype.getClassName = function () {
  82375. return "WebVRFreeCamera";
  82376. };
  82377. /**
  82378. * Calls resetPose on the vrDisplay
  82379. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  82380. */
  82381. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  82382. //uses the vrDisplay's "resetPose()".
  82383. //pitch and roll won't be affected.
  82384. this._vrDevice.resetPose();
  82385. };
  82386. /**
  82387. * Updates the rig cameras (left and right eye)
  82388. */
  82389. WebVRFreeCamera.prototype._updateRigCameras = function () {
  82390. var camLeft = this._rigCameras[0];
  82391. var camRight = this._rigCameras[1];
  82392. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82393. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  82394. camLeft.position.copyFrom(this._deviceRoomPosition);
  82395. camRight.position.copyFrom(this._deviceRoomPosition);
  82396. };
  82397. /**
  82398. * Updates the cached values of the camera
  82399. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  82400. */
  82401. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  82402. var _this = this;
  82403. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  82404. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  82405. if (!this.updateCacheCalled) {
  82406. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  82407. this.updateCacheCalled = true;
  82408. this.update();
  82409. }
  82410. // Set working vector to the device position in room space rotated by the new rotation
  82411. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  82412. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  82413. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  82414. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  82415. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  82416. // Add translation from anchor position
  82417. this._deviceToWorld.getTranslationToRef(this._workingVector);
  82418. this._workingVector.addInPlace(this.position);
  82419. this._workingVector.subtractInPlace(this._cache.position);
  82420. this._deviceToWorld.setTranslation(this._workingVector);
  82421. // Set an inverted matrix to be used when updating the camera
  82422. this._deviceToWorld.invertToRef(this._worldToDevice);
  82423. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  82424. this.controllers.forEach(function (controller) {
  82425. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  82426. controller.update();
  82427. });
  82428. }
  82429. if (!ignoreParentClass) {
  82430. _super.prototype._updateCache.call(this);
  82431. }
  82432. this.updateCacheCalled = false;
  82433. };
  82434. /**
  82435. * Updates the current device position and rotation in the babylon world
  82436. */
  82437. WebVRFreeCamera.prototype.update = function () {
  82438. // Get current device position in babylon world
  82439. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  82440. // Get current device rotation in babylon world
  82441. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  82442. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  82443. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  82444. _super.prototype.update.call(this);
  82445. };
  82446. /**
  82447. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  82448. * @returns an identity matrix
  82449. */
  82450. WebVRFreeCamera.prototype._getViewMatrix = function () {
  82451. return BABYLON.Matrix.Identity();
  82452. };
  82453. /**
  82454. * This function is called by the two RIG cameras.
  82455. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  82456. */
  82457. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  82458. var _this = this;
  82459. // Update the parent camera prior to using a child camera to avoid desynchronization
  82460. var parentCamera = this._cameraRigParams["parentCamera"];
  82461. parentCamera._updateCache();
  82462. //WebVR 1.1
  82463. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  82464. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  82465. if (!this.getScene().useRightHandedSystem) {
  82466. [2, 6, 8, 9, 14].forEach(function (num) {
  82467. _this._webvrViewMatrix.m[num] *= -1;
  82468. });
  82469. }
  82470. // update the camera rotation matrix
  82471. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  82472. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  82473. // Computing target and final matrix
  82474. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  82475. // should the view matrix be updated with scale and position offset?
  82476. if (parentCamera.deviceScaleFactor !== 1) {
  82477. this._webvrViewMatrix.invert();
  82478. // scale the position, if set
  82479. if (parentCamera.deviceScaleFactor) {
  82480. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  82481. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  82482. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  82483. }
  82484. this._webvrViewMatrix.invert();
  82485. }
  82486. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  82487. return this._webvrViewMatrix;
  82488. };
  82489. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  82490. var _this = this;
  82491. var parentCamera = this.parent;
  82492. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  82493. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  82494. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  82495. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  82496. //babylon compatible matrix
  82497. if (!this.getScene().useRightHandedSystem) {
  82498. [8, 9, 10, 11].forEach(function (num) {
  82499. _this._projectionMatrix.m[num] *= -1;
  82500. });
  82501. }
  82502. return this._projectionMatrix;
  82503. };
  82504. /**
  82505. * Initializes the controllers and their meshes
  82506. */
  82507. WebVRFreeCamera.prototype.initControllers = function () {
  82508. var _this = this;
  82509. this.controllers = [];
  82510. var manager = this.getScene().gamepadManager;
  82511. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  82512. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82513. var webVrController = gamepad;
  82514. if (webVrController.defaultModel) {
  82515. webVrController.defaultModel.setEnabled(false);
  82516. }
  82517. if (webVrController.hand === "right") {
  82518. _this._rightController = null;
  82519. }
  82520. if (webVrController.hand === "left") {
  82521. _this._leftController = null;
  82522. }
  82523. var controllerIndex = _this.controllers.indexOf(webVrController);
  82524. if (controllerIndex !== -1) {
  82525. _this.controllers.splice(controllerIndex, 1);
  82526. }
  82527. }
  82528. });
  82529. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  82530. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  82531. var webVrController_1 = gamepad;
  82532. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  82533. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  82534. if (_this.webVROptions.controllerMeshes) {
  82535. if (webVrController_1.defaultModel) {
  82536. webVrController_1.defaultModel.setEnabled(true);
  82537. }
  82538. else {
  82539. // Load the meshes
  82540. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82541. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82542. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82543. if (_this.webVROptions.defaultLightingOnControllers) {
  82544. if (!_this._lightOnControllers) {
  82545. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82546. }
  82547. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82548. var children = mesh.getChildren();
  82549. if (children.length !== 0) {
  82550. children.forEach(function (mesh) {
  82551. light.includedOnlyMeshes.push(mesh);
  82552. activateLightOnSubMeshes_1(mesh, light);
  82553. });
  82554. }
  82555. };
  82556. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82557. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82558. }
  82559. });
  82560. }
  82561. }
  82562. webVrController_1.attachToPoseControlledCamera(_this);
  82563. // since this is async - sanity check. Is the controller already stored?
  82564. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82565. //add to the controllers array
  82566. _this.controllers.push(webVrController_1);
  82567. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82568. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82569. // So we're overriding setting left & right manually to be sure
  82570. var firstViveWandDetected = false;
  82571. for (var i = 0; i < _this.controllers.length; i++) {
  82572. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82573. if (!firstViveWandDetected) {
  82574. firstViveWandDetected = true;
  82575. _this.controllers[i].hand = "left";
  82576. }
  82577. else {
  82578. _this.controllers[i].hand = "right";
  82579. }
  82580. }
  82581. }
  82582. //did we find enough controllers? Great! let the developer know.
  82583. if (_this.controllers.length >= 2) {
  82584. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82585. }
  82586. }
  82587. }
  82588. });
  82589. };
  82590. return WebVRFreeCamera;
  82591. }(BABYLON.FreeCamera));
  82592. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82593. })(BABYLON || (BABYLON = {}));
  82594. //# sourceMappingURL=babylon.webVRCamera.js.map
  82595. "use strict";
  82596. var BABYLON;
  82597. (function (BABYLON) {
  82598. // We're mainly based on the logic defined into the FreeCamera code
  82599. /**
  82600. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82601. * being tilted forward or back and left or right.
  82602. */
  82603. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82604. __extends(DeviceOrientationCamera, _super);
  82605. /**
  82606. * Creates a new device orientation camera
  82607. * @param name The name of the camera
  82608. * @param position The start position camera
  82609. * @param scene The scene the camera belongs to
  82610. */
  82611. function DeviceOrientationCamera(name, position, scene) {
  82612. var _this = _super.call(this, name, position, scene) || this;
  82613. _this._quaternionCache = new BABYLON.Quaternion();
  82614. _this.inputs.addDeviceOrientation();
  82615. return _this;
  82616. }
  82617. /**
  82618. * Gets the current instance class name ("DeviceOrientationCamera").
  82619. * This helps avoiding instanceof at run time.
  82620. * @returns the class name
  82621. */
  82622. DeviceOrientationCamera.prototype.getClassName = function () {
  82623. return "DeviceOrientationCamera";
  82624. };
  82625. /**
  82626. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82627. */
  82628. DeviceOrientationCamera.prototype._checkInputs = function () {
  82629. _super.prototype._checkInputs.call(this);
  82630. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82631. if (this._initialQuaternion) {
  82632. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82633. }
  82634. };
  82635. /**
  82636. * Reset the camera to its default orientation on the specified axis only.
  82637. * @param axis The axis to reset
  82638. */
  82639. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82640. var _this = this;
  82641. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82642. //can only work if this camera has a rotation quaternion already.
  82643. if (!this.rotationQuaternion)
  82644. return;
  82645. if (!this._initialQuaternion) {
  82646. this._initialQuaternion = new BABYLON.Quaternion();
  82647. }
  82648. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82649. ['x', 'y', 'z'].forEach(function (axisName) {
  82650. if (!axis[axisName]) {
  82651. _this._initialQuaternion[axisName] = 0;
  82652. }
  82653. else {
  82654. _this._initialQuaternion[axisName] *= -1;
  82655. }
  82656. });
  82657. this._initialQuaternion.normalize();
  82658. //force rotation update
  82659. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82660. };
  82661. return DeviceOrientationCamera;
  82662. }(BABYLON.FreeCamera));
  82663. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82664. })(BABYLON || (BABYLON = {}));
  82665. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82666. "use strict";
  82667. var BABYLON;
  82668. (function (BABYLON) {
  82669. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82670. __extends(VRDeviceOrientationFreeCamera, _super);
  82671. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82672. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82673. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82674. var _this = _super.call(this, name, position, scene) || this;
  82675. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82676. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82677. return _this;
  82678. }
  82679. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82680. return "VRDeviceOrientationFreeCamera";
  82681. };
  82682. return VRDeviceOrientationFreeCamera;
  82683. }(BABYLON.DeviceOrientationCamera));
  82684. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82685. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82686. __extends(VRDeviceOrientationGamepadCamera, _super);
  82687. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82688. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82689. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82690. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82691. _this.inputs.addGamepad();
  82692. return _this;
  82693. }
  82694. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82695. return "VRDeviceOrientationGamepadCamera";
  82696. };
  82697. return VRDeviceOrientationGamepadCamera;
  82698. }(VRDeviceOrientationFreeCamera));
  82699. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82700. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82701. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82702. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82703. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82704. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82705. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82706. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82707. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82708. _this.inputs.addVRDeviceOrientation();
  82709. return _this;
  82710. }
  82711. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82712. return "VRDeviceOrientationArcRotateCamera";
  82713. };
  82714. return VRDeviceOrientationArcRotateCamera;
  82715. }(BABYLON.ArcRotateCamera));
  82716. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82717. })(BABYLON || (BABYLON = {}));
  82718. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82719. "use strict";
  82720. var BABYLON;
  82721. (function (BABYLON) {
  82722. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82723. __extends(AnaglyphFreeCamera, _super);
  82724. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82725. var _this = _super.call(this, name, position, scene) || this;
  82726. _this.interaxialDistance = interaxialDistance;
  82727. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82728. return _this;
  82729. }
  82730. AnaglyphFreeCamera.prototype.getClassName = function () {
  82731. return "AnaglyphFreeCamera";
  82732. };
  82733. return AnaglyphFreeCamera;
  82734. }(BABYLON.FreeCamera));
  82735. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82736. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82737. __extends(AnaglyphArcRotateCamera, _super);
  82738. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82739. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82740. _this.interaxialDistance = interaxialDistance;
  82741. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82742. return _this;
  82743. }
  82744. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82745. return "AnaglyphArcRotateCamera";
  82746. };
  82747. return AnaglyphArcRotateCamera;
  82748. }(BABYLON.ArcRotateCamera));
  82749. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82750. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82751. __extends(AnaglyphGamepadCamera, _super);
  82752. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82753. var _this = _super.call(this, name, position, scene) || this;
  82754. _this.interaxialDistance = interaxialDistance;
  82755. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82756. return _this;
  82757. }
  82758. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82759. return "AnaglyphGamepadCamera";
  82760. };
  82761. return AnaglyphGamepadCamera;
  82762. }(BABYLON.GamepadCamera));
  82763. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82764. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82765. __extends(AnaglyphUniversalCamera, _super);
  82766. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82767. var _this = _super.call(this, name, position, scene) || this;
  82768. _this.interaxialDistance = interaxialDistance;
  82769. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82770. return _this;
  82771. }
  82772. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82773. return "AnaglyphUniversalCamera";
  82774. };
  82775. return AnaglyphUniversalCamera;
  82776. }(BABYLON.UniversalCamera));
  82777. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82778. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82779. __extends(StereoscopicFreeCamera, _super);
  82780. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82781. var _this = _super.call(this, name, position, scene) || this;
  82782. _this.interaxialDistance = interaxialDistance;
  82783. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82784. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82785. return _this;
  82786. }
  82787. StereoscopicFreeCamera.prototype.getClassName = function () {
  82788. return "StereoscopicFreeCamera";
  82789. };
  82790. return StereoscopicFreeCamera;
  82791. }(BABYLON.FreeCamera));
  82792. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82793. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82794. __extends(StereoscopicArcRotateCamera, _super);
  82795. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82796. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82797. _this.interaxialDistance = interaxialDistance;
  82798. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82799. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82800. return _this;
  82801. }
  82802. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82803. return "StereoscopicArcRotateCamera";
  82804. };
  82805. return StereoscopicArcRotateCamera;
  82806. }(BABYLON.ArcRotateCamera));
  82807. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82808. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82809. __extends(StereoscopicGamepadCamera, _super);
  82810. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82811. var _this = _super.call(this, name, position, scene) || this;
  82812. _this.interaxialDistance = interaxialDistance;
  82813. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82814. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82815. return _this;
  82816. }
  82817. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82818. return "StereoscopicGamepadCamera";
  82819. };
  82820. return StereoscopicGamepadCamera;
  82821. }(BABYLON.GamepadCamera));
  82822. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82823. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82824. __extends(StereoscopicUniversalCamera, _super);
  82825. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82826. var _this = _super.call(this, name, position, scene) || this;
  82827. _this.interaxialDistance = interaxialDistance;
  82828. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82829. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82830. return _this;
  82831. }
  82832. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82833. return "StereoscopicUniversalCamera";
  82834. };
  82835. return StereoscopicUniversalCamera;
  82836. }(BABYLON.UniversalCamera));
  82837. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82838. })(BABYLON || (BABYLON = {}));
  82839. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82840. "use strict";
  82841. var BABYLON;
  82842. (function (BABYLON) {
  82843. var VRExperienceHelperGazer = /** @class */ (function () {
  82844. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82845. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82846. this.scene = scene;
  82847. this._pointerDownOnMeshAsked = false;
  82848. this._isActionableMesh = false;
  82849. this._teleportationRequestInitiated = false;
  82850. this._teleportationBackRequestInitiated = false;
  82851. this._dpadPressed = true;
  82852. this._activePointer = false;
  82853. this._id = VRExperienceHelperGazer._idCounter++;
  82854. // Gaze tracker
  82855. if (!gazeTrackerToClone) {
  82856. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82857. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82858. this._gazeTracker.isPickable = false;
  82859. this._gazeTracker.isVisible = false;
  82860. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82861. targetMat.specularColor = BABYLON.Color3.Black();
  82862. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82863. targetMat.backFaceCulling = false;
  82864. this._gazeTracker.material = targetMat;
  82865. }
  82866. else {
  82867. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82868. }
  82869. }
  82870. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82871. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82872. };
  82873. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82874. this._pointerDownOnMeshAsked = true;
  82875. if (this._currentMeshSelected && this._currentHit) {
  82876. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82877. }
  82878. };
  82879. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82880. if (this._currentMeshSelected && this._currentHit) {
  82881. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82882. }
  82883. this._pointerDownOnMeshAsked = false;
  82884. };
  82885. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82886. this._activePointer = true;
  82887. };
  82888. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82889. this._activePointer = false;
  82890. };
  82891. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82892. };
  82893. VRExperienceHelperGazer.prototype.dispose = function () {
  82894. this._interactionsEnabled = false;
  82895. this._teleportationEnabled = false;
  82896. };
  82897. VRExperienceHelperGazer._idCounter = 0;
  82898. return VRExperienceHelperGazer;
  82899. }());
  82900. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82901. __extends(VRExperienceHelperControllerGazer, _super);
  82902. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82903. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82904. _this.webVRController = webVRController;
  82905. // Laser pointer
  82906. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82907. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82908. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82909. laserPointerMaterial.alpha = 0.6;
  82910. _this._laserPointer.material = laserPointerMaterial;
  82911. _this._laserPointer.rotation.x = Math.PI / 2;
  82912. _this._laserPointer.position.z = -0.5;
  82913. _this._laserPointer.isVisible = false;
  82914. if (!webVRController.mesh) {
  82915. // Create an empty mesh that is used prior to loading the high quality model
  82916. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82917. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82918. preloadPointerPose.rotation.x = -0.7;
  82919. preloadMesh.addChild(preloadPointerPose);
  82920. webVRController.attachToMesh(preloadMesh);
  82921. }
  82922. _this._setLaserPointerParent(webVRController.mesh);
  82923. return _this;
  82924. }
  82925. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82926. return this.webVRController.getForwardRay(length);
  82927. };
  82928. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82929. _super.prototype._activatePointer.call(this);
  82930. this._laserPointer.isVisible = true;
  82931. };
  82932. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82933. _super.prototype._deactivatePointer.call(this);
  82934. this._laserPointer.isVisible = false;
  82935. };
  82936. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82937. this._laserPointer.material.emissiveColor = color;
  82938. };
  82939. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82940. var makeNotPick = function (root) {
  82941. root.name += " laserPointer";
  82942. root.getChildMeshes().forEach(function (c) {
  82943. makeNotPick(c);
  82944. });
  82945. };
  82946. makeNotPick(mesh);
  82947. var childMeshes = mesh.getChildMeshes();
  82948. this.webVRController._pointingPoseNode = null;
  82949. for (var i = 0; i < childMeshes.length; i++) {
  82950. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82951. mesh = childMeshes[i];
  82952. this.webVRController._pointingPoseNode = mesh;
  82953. break;
  82954. }
  82955. }
  82956. this._laserPointer.parent = mesh;
  82957. };
  82958. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82959. this._laserPointer.scaling.y = distance;
  82960. this._laserPointer.position.z = -distance / 2;
  82961. };
  82962. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82963. _super.prototype.dispose.call(this);
  82964. this._laserPointer.dispose();
  82965. };
  82966. return VRExperienceHelperControllerGazer;
  82967. }(VRExperienceHelperGazer));
  82968. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82969. __extends(VRExperienceHelperCameraGazer, _super);
  82970. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82971. var _this = _super.call(this, scene) || this;
  82972. _this.getCamera = getCamera;
  82973. return _this;
  82974. }
  82975. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82976. var camera = this.getCamera();
  82977. if (camera) {
  82978. return camera.getForwardRay(length);
  82979. }
  82980. else {
  82981. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82982. }
  82983. };
  82984. return VRExperienceHelperCameraGazer;
  82985. }(VRExperienceHelperGazer));
  82986. /**
  82987. * Helps to quickly add VR support to an existing scene.
  82988. * See http://doc.babylonjs.com/how_to/webvr_helper
  82989. */
  82990. var VRExperienceHelper = /** @class */ (function () {
  82991. /**
  82992. * Instantiates a VRExperienceHelper.
  82993. * Helps to quickly add VR support to an existing scene.
  82994. * @param scene The scene the VRExperienceHelper belongs to.
  82995. * @param webVROptions Options to modify the vr experience helper's behavior.
  82996. */
  82997. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82998. if (webVROptions === void 0) { webVROptions = {}; }
  82999. var _this = this;
  83000. this.webVROptions = webVROptions;
  83001. // Can the system support WebVR, even if a headset isn't plugged in?
  83002. this._webVRsupported = false;
  83003. // If WebVR is supported, is a headset plugged in and are we ready to present?
  83004. this._webVRready = false;
  83005. // Are we waiting for the requestPresent callback to complete?
  83006. this._webVRrequesting = false;
  83007. // Are we presenting to the headset right now?
  83008. this._webVRpresenting = false;
  83009. // Are we presenting in the fullscreen fallback?
  83010. this._fullscreenVRpresenting = false;
  83011. /**
  83012. * Observable raised when entering VR.
  83013. */
  83014. this.onEnteringVRObservable = new BABYLON.Observable();
  83015. /**
  83016. * Observable raised when exiting VR.
  83017. */
  83018. this.onExitingVRObservable = new BABYLON.Observable();
  83019. /**
  83020. * Observable raised when controller mesh is loaded.
  83021. */
  83022. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  83023. this._useCustomVRButton = false;
  83024. this._teleportationRequested = false;
  83025. this._teleportActive = false;
  83026. this._floorMeshesCollection = [];
  83027. this._rotationAllowed = true;
  83028. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  83029. this._rotationRightAsked = false;
  83030. this._rotationLeftAsked = false;
  83031. this._isDefaultTeleportationTarget = true;
  83032. this._teleportationFillColor = "#444444";
  83033. this._teleportationBorderColor = "#FFFFFF";
  83034. this._rotationAngle = 0;
  83035. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  83036. this._padSensibilityUp = 0.65;
  83037. this._padSensibilityDown = 0.35;
  83038. this.leftController = null;
  83039. this.rightController = null;
  83040. /**
  83041. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  83042. */
  83043. this.onNewMeshSelected = new BABYLON.Observable();
  83044. /**
  83045. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  83046. */
  83047. this.onNewMeshPicked = new BABYLON.Observable();
  83048. /**
  83049. * Observable raised before camera teleportation
  83050. */
  83051. this.onBeforeCameraTeleport = new BABYLON.Observable();
  83052. /**
  83053. * Observable raised after camera teleportation
  83054. */
  83055. this.onAfterCameraTeleport = new BABYLON.Observable();
  83056. /**
  83057. * Observable raised when current selected mesh gets unselected
  83058. */
  83059. this.onSelectedMeshUnselected = new BABYLON.Observable();
  83060. /**
  83061. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  83062. */
  83063. this.teleportationEnabled = true;
  83064. this._teleportationInitialized = false;
  83065. this._interactionsEnabled = false;
  83066. this._interactionsRequested = false;
  83067. this._displayGaze = true;
  83068. this._displayLaserPointer = true;
  83069. this._onResize = function () {
  83070. _this.moveButtonToBottomRight();
  83071. if (_this._fullscreenVRpresenting && _this._webVRready) {
  83072. _this.exitVR();
  83073. }
  83074. };
  83075. this._onFullscreenChange = function () {
  83076. if (document.fullscreen !== undefined) {
  83077. _this._fullscreenVRpresenting = document.fullscreen;
  83078. }
  83079. else if (document.mozFullScreen !== undefined) {
  83080. _this._fullscreenVRpresenting = document.mozFullScreen;
  83081. }
  83082. else if (document.webkitIsFullScreen !== undefined) {
  83083. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  83084. }
  83085. else if (document.msIsFullScreen !== undefined) {
  83086. _this._fullscreenVRpresenting = document.msIsFullScreen;
  83087. }
  83088. if (!_this._fullscreenVRpresenting && _this._canvas) {
  83089. _this.exitVR();
  83090. if (!_this._useCustomVRButton) {
  83091. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  83092. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  83093. }
  83094. }
  83095. };
  83096. this.beforeRender = function () {
  83097. if (_this.leftController && _this.leftController._activePointer) {
  83098. _this._castRayAndSelectObject(_this.leftController);
  83099. }
  83100. if (_this.rightController && _this.rightController._activePointer) {
  83101. _this._castRayAndSelectObject(_this.rightController);
  83102. }
  83103. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  83104. _this._castRayAndSelectObject(_this._cameraGazer);
  83105. }
  83106. else {
  83107. _this._cameraGazer._gazeTracker.isVisible = false;
  83108. }
  83109. };
  83110. this._onNewGamepadConnected = function (gamepad) {
  83111. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  83112. if (gamepad.leftStick) {
  83113. gamepad.onleftstickchanged(function (stickValues) {
  83114. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  83115. // Listening to classic/xbox gamepad only if no VR controller is active
  83116. if ((!_this.leftController && !_this.rightController) ||
  83117. ((_this.leftController && !_this.leftController._activePointer) &&
  83118. (_this.rightController && !_this.rightController._activePointer))) {
  83119. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  83120. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  83121. }
  83122. }
  83123. });
  83124. }
  83125. if (gamepad.rightStick) {
  83126. gamepad.onrightstickchanged(function (stickValues) {
  83127. if (_this._teleportationInitialized) {
  83128. _this._checkRotate(stickValues, _this._cameraGazer);
  83129. }
  83130. });
  83131. }
  83132. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  83133. gamepad.onbuttondown(function (buttonPressed) {
  83134. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83135. _this._cameraGazer._selectionPointerDown();
  83136. }
  83137. });
  83138. gamepad.onbuttonup(function (buttonPressed) {
  83139. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  83140. _this._cameraGazer._selectionPointerUp();
  83141. }
  83142. });
  83143. }
  83144. }
  83145. else {
  83146. var webVRController = gamepad;
  83147. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  83148. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  83149. _this.rightController = controller;
  83150. }
  83151. else {
  83152. _this.leftController = controller;
  83153. }
  83154. _this._tryEnableInteractionOnController(controller);
  83155. }
  83156. };
  83157. // 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
  83158. this._tryEnableInteractionOnController = function (controller) {
  83159. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  83160. _this._enableInteractionOnController(controller);
  83161. }
  83162. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  83163. _this._enableTeleportationOnController(controller);
  83164. }
  83165. };
  83166. this._onNewGamepadDisconnected = function (gamepad) {
  83167. if (gamepad instanceof BABYLON.WebVRController) {
  83168. if (gamepad.hand === "left" && _this.leftController != null) {
  83169. _this.leftController.dispose();
  83170. _this.leftController = null;
  83171. }
  83172. if (gamepad.hand === "right" && _this.rightController != null) {
  83173. _this.rightController.dispose();
  83174. _this.rightController = null;
  83175. }
  83176. }
  83177. };
  83178. this._workingVector = BABYLON.Vector3.Zero();
  83179. this._workingQuaternion = BABYLON.Quaternion.Identity();
  83180. this._workingMatrix = BABYLON.Matrix.Identity();
  83181. this._scene = scene;
  83182. this._canvas = scene.getEngine().getRenderingCanvas();
  83183. // Parse options
  83184. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  83185. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  83186. }
  83187. if (webVROptions.createDeviceOrientationCamera === undefined) {
  83188. webVROptions.createDeviceOrientationCamera = true;
  83189. }
  83190. if (webVROptions.defaultHeight === undefined) {
  83191. webVROptions.defaultHeight = 1.7;
  83192. }
  83193. if (webVROptions.useCustomVRButton) {
  83194. this._useCustomVRButton = true;
  83195. if (webVROptions.customVRButton) {
  83196. this._btnVR = webVROptions.customVRButton;
  83197. }
  83198. }
  83199. if (webVROptions.rayLength) {
  83200. this._rayLength = webVROptions.rayLength;
  83201. }
  83202. this._defaultHeight = webVROptions.defaultHeight;
  83203. if (webVROptions.positionScale) {
  83204. this._rayLength *= webVROptions.positionScale;
  83205. this._defaultHeight *= webVROptions.positionScale;
  83206. }
  83207. // Set position
  83208. if (this._scene.activeCamera) {
  83209. this._position = this._scene.activeCamera.position.clone();
  83210. }
  83211. else {
  83212. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  83213. }
  83214. // Set non-vr camera
  83215. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  83216. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  83217. // Copy data from existing camera
  83218. if (this._scene.activeCamera) {
  83219. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  83220. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  83221. // Set rotation from previous camera
  83222. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  83223. var targetCamera = this._scene.activeCamera;
  83224. if (targetCamera.rotationQuaternion) {
  83225. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  83226. }
  83227. else {
  83228. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  83229. }
  83230. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  83231. }
  83232. }
  83233. this._scene.activeCamera = this._deviceOrientationCamera;
  83234. if (this._canvas) {
  83235. this._scene.activeCamera.attachControl(this._canvas);
  83236. }
  83237. }
  83238. else {
  83239. this._existingCamera = this._scene.activeCamera;
  83240. }
  83241. // Create VR cameras
  83242. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83243. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  83244. }
  83245. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  83246. this._webVRCamera.useStandingMatrix();
  83247. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  83248. // Create default button
  83249. if (!this._useCustomVRButton) {
  83250. this._btnVR = document.createElement("BUTTON");
  83251. this._btnVR.className = "babylonVRicon";
  83252. this._btnVR.id = "babylonVRiconbtn";
  83253. this._btnVR.title = "Click to switch to VR";
  83254. 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) }";
  83255. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  83256. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  83257. // css += ".babylonVRicon.vrdisplaysupported { }";
  83258. // css += ".babylonVRicon.vrdisplayready { }";
  83259. // css += ".babylonVRicon.vrdisplayrequesting { }";
  83260. var style = document.createElement('style');
  83261. style.appendChild(document.createTextNode(css));
  83262. document.getElementsByTagName('head')[0].appendChild(style);
  83263. this.moveButtonToBottomRight();
  83264. }
  83265. // VR button click event
  83266. if (this._btnVR) {
  83267. this._btnVR.addEventListener("click", function () {
  83268. if (!_this.isInVRMode) {
  83269. _this.enterVR();
  83270. }
  83271. else {
  83272. _this.exitVR();
  83273. }
  83274. });
  83275. }
  83276. // Window events
  83277. window.addEventListener("resize", this._onResize);
  83278. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  83279. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  83280. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  83281. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  83282. // Display vr button when headset is connected
  83283. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  83284. this.displayVRButton();
  83285. }
  83286. else {
  83287. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  83288. if (e.vrDisplay) {
  83289. _this.displayVRButton();
  83290. }
  83291. });
  83292. }
  83293. // Exiting VR mode using 'ESC' key on desktop
  83294. this._onKeyDown = function (event) {
  83295. if (event.keyCode === 27 && _this.isInVRMode) {
  83296. _this.exitVR();
  83297. }
  83298. };
  83299. document.addEventListener("keydown", this._onKeyDown);
  83300. // Exiting VR mode double tapping the touch screen
  83301. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  83302. if (_this.isInVRMode) {
  83303. _this.exitVR();
  83304. if (_this._fullscreenVRpresenting) {
  83305. _this._scene.getEngine().switchFullscreen(true);
  83306. }
  83307. }
  83308. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  83309. // Listen for WebVR display changes
  83310. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  83311. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  83312. this._onVRRequestPresentStart = function () {
  83313. _this._webVRrequesting = true;
  83314. _this.updateButtonVisibility();
  83315. };
  83316. this._onVRRequestPresentComplete = function (success) {
  83317. _this._webVRrequesting = false;
  83318. _this.updateButtonVisibility();
  83319. };
  83320. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  83321. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  83322. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  83323. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83324. scene.onDisposeObservable.add(function () {
  83325. _this.dispose();
  83326. });
  83327. // Gamepad connection events
  83328. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  83329. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  83330. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  83331. this.updateButtonVisibility();
  83332. //create easing functions
  83333. this._circleEase = new BABYLON.CircleEase();
  83334. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83335. }
  83336. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  83337. /** Return this.onEnteringVRObservable
  83338. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  83339. */
  83340. get: function () {
  83341. return this.onEnteringVRObservable;
  83342. },
  83343. enumerable: true,
  83344. configurable: true
  83345. });
  83346. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  83347. /** Return this.onExitingVRObservable
  83348. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  83349. */
  83350. get: function () {
  83351. return this.onExitingVRObservable;
  83352. },
  83353. enumerable: true,
  83354. configurable: true
  83355. });
  83356. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  83357. /** Return this.onControllerMeshLoadedObservable
  83358. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  83359. */
  83360. get: function () {
  83361. return this.onControllerMeshLoadedObservable;
  83362. },
  83363. enumerable: true,
  83364. configurable: true
  83365. });
  83366. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  83367. /**
  83368. * The mesh used to display where the user is going to teleport.
  83369. */
  83370. get: function () {
  83371. return this._teleportationTarget;
  83372. },
  83373. /**
  83374. * Sets the mesh to be used to display where the user is going to teleport.
  83375. */
  83376. set: function (value) {
  83377. if (value) {
  83378. value.name = "teleportationTarget";
  83379. this._isDefaultTeleportationTarget = false;
  83380. this._teleportationTarget = value;
  83381. }
  83382. },
  83383. enumerable: true,
  83384. configurable: true
  83385. });
  83386. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  83387. /**
  83388. * The mesh used to display where the user is selecting,
  83389. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  83390. * See http://doc.babylonjs.com/resources/baking_transformations
  83391. */
  83392. get: function () {
  83393. return this._cameraGazer._gazeTracker;
  83394. },
  83395. set: function (value) {
  83396. if (value) {
  83397. this._cameraGazer._gazeTracker = value;
  83398. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  83399. this._cameraGazer._gazeTracker.isPickable = false;
  83400. this._cameraGazer._gazeTracker.isVisible = false;
  83401. this._cameraGazer._gazeTracker.name = "gazeTracker";
  83402. if (this.leftController) {
  83403. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83404. }
  83405. if (this.rightController) {
  83406. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  83407. }
  83408. }
  83409. },
  83410. enumerable: true,
  83411. configurable: true
  83412. });
  83413. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  83414. /**
  83415. * If the ray of the gaze should be displayed.
  83416. */
  83417. get: function () {
  83418. return this._displayGaze;
  83419. },
  83420. /**
  83421. * Sets if the ray of the gaze should be displayed.
  83422. */
  83423. set: function (value) {
  83424. this._displayGaze = value;
  83425. if (!value) {
  83426. this._cameraGazer._gazeTracker.isVisible = false;
  83427. if (this.leftController) {
  83428. this.leftController._gazeTracker.isVisible = false;
  83429. }
  83430. if (this.rightController) {
  83431. this.rightController._gazeTracker.isVisible = false;
  83432. }
  83433. }
  83434. },
  83435. enumerable: true,
  83436. configurable: true
  83437. });
  83438. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  83439. /**
  83440. * If the ray of the LaserPointer should be displayed.
  83441. */
  83442. get: function () {
  83443. return this._displayLaserPointer;
  83444. },
  83445. /**
  83446. * Sets if the ray of the LaserPointer should be displayed.
  83447. */
  83448. set: function (value) {
  83449. this._displayLaserPointer = value;
  83450. if (!value) {
  83451. if (this.rightController) {
  83452. this.rightController._deactivatePointer();
  83453. this.rightController._gazeTracker.isVisible = false;
  83454. }
  83455. if (this.leftController) {
  83456. this.leftController._deactivatePointer();
  83457. this.leftController._gazeTracker.isVisible = false;
  83458. }
  83459. }
  83460. else {
  83461. if (this.rightController) {
  83462. this.rightController._activatePointer();
  83463. }
  83464. else if (this.leftController) {
  83465. this.leftController._activatePointer();
  83466. }
  83467. }
  83468. },
  83469. enumerable: true,
  83470. configurable: true
  83471. });
  83472. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  83473. /**
  83474. * The deviceOrientationCamera used as the camera when not in VR.
  83475. */
  83476. get: function () {
  83477. return this._deviceOrientationCamera;
  83478. },
  83479. enumerable: true,
  83480. configurable: true
  83481. });
  83482. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  83483. /**
  83484. * Based on the current WebVR support, returns the current VR camera used.
  83485. */
  83486. get: function () {
  83487. if (this._webVRready) {
  83488. return this._webVRCamera;
  83489. }
  83490. else {
  83491. return this._scene.activeCamera;
  83492. }
  83493. },
  83494. enumerable: true,
  83495. configurable: true
  83496. });
  83497. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  83498. /**
  83499. * The webVRCamera which is used when in VR.
  83500. */
  83501. get: function () {
  83502. return this._webVRCamera;
  83503. },
  83504. enumerable: true,
  83505. configurable: true
  83506. });
  83507. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  83508. /**
  83509. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  83510. */
  83511. get: function () {
  83512. return this._vrDeviceOrientationCamera;
  83513. },
  83514. enumerable: true,
  83515. configurable: true
  83516. });
  83517. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  83518. get: function () {
  83519. var result = this._cameraGazer._teleportationRequestInitiated
  83520. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  83521. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  83522. return result;
  83523. },
  83524. enumerable: true,
  83525. configurable: true
  83526. });
  83527. // Raised when one of the controller has loaded successfully its associated default mesh
  83528. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  83529. if (this.leftController && this.leftController.webVRController == webVRController) {
  83530. if (webVRController.mesh) {
  83531. this.leftController._setLaserPointerParent(webVRController.mesh);
  83532. }
  83533. }
  83534. if (this.rightController && this.rightController.webVRController == webVRController) {
  83535. if (webVRController.mesh) {
  83536. this.rightController._setLaserPointerParent(webVRController.mesh);
  83537. }
  83538. }
  83539. try {
  83540. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83541. }
  83542. catch (err) {
  83543. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83544. }
  83545. };
  83546. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83547. /**
  83548. * Gets a value indicating if we are currently in VR mode.
  83549. */
  83550. get: function () {
  83551. return this._webVRpresenting || this._fullscreenVRpresenting;
  83552. },
  83553. enumerable: true,
  83554. configurable: true
  83555. });
  83556. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83557. var vrDisplay = this._scene.getEngine().getVRDevice();
  83558. if (vrDisplay) {
  83559. var wasPresenting = this._webVRpresenting;
  83560. // A VR display is connected
  83561. this._webVRpresenting = vrDisplay.isPresenting;
  83562. if (wasPresenting && !this._webVRpresenting)
  83563. this.exitVR();
  83564. }
  83565. else {
  83566. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83567. }
  83568. this.updateButtonVisibility();
  83569. };
  83570. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83571. this._webVRsupported = eventArgs.vrSupported;
  83572. this._webVRready = !!eventArgs.vrDisplay;
  83573. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83574. this.updateButtonVisibility();
  83575. };
  83576. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83577. if (this._canvas && !this._useCustomVRButton) {
  83578. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83579. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83580. }
  83581. };
  83582. VRExperienceHelper.prototype.displayVRButton = function () {
  83583. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83584. document.body.appendChild(this._btnVR);
  83585. this._btnVRDisplayed = true;
  83586. }
  83587. };
  83588. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83589. if (!this._btnVR || this._useCustomVRButton) {
  83590. return;
  83591. }
  83592. this._btnVR.className = "babylonVRicon";
  83593. if (this.isInVRMode) {
  83594. this._btnVR.className += " vrdisplaypresenting";
  83595. }
  83596. else {
  83597. if (this._webVRready)
  83598. this._btnVR.className += " vrdisplayready";
  83599. if (this._webVRsupported)
  83600. this._btnVR.className += " vrdisplaysupported";
  83601. if (this._webVRrequesting)
  83602. this._btnVR.className += " vrdisplayrequesting";
  83603. }
  83604. };
  83605. /**
  83606. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83607. * Otherwise, will use the fullscreen API.
  83608. */
  83609. VRExperienceHelper.prototype.enterVR = function () {
  83610. if (this.onEnteringVRObservable) {
  83611. try {
  83612. this.onEnteringVRObservable.notifyObservers(this);
  83613. }
  83614. catch (err) {
  83615. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83616. }
  83617. }
  83618. if (this._scene.activeCamera) {
  83619. this._position = this._scene.activeCamera.position.clone();
  83620. // make sure that we return to the last active camera
  83621. this._existingCamera = this._scene.activeCamera;
  83622. }
  83623. if (this._webVRrequesting)
  83624. return;
  83625. // If WebVR is supported and a headset is connected
  83626. if (this._webVRready) {
  83627. if (!this._webVRpresenting) {
  83628. this._webVRCamera.position = this._position;
  83629. this._scene.activeCamera = this._webVRCamera;
  83630. }
  83631. }
  83632. else if (this._vrDeviceOrientationCamera) {
  83633. this._vrDeviceOrientationCamera.position = this._position;
  83634. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83635. this._scene.getEngine().switchFullscreen(true);
  83636. this.updateButtonVisibility();
  83637. }
  83638. if (this._scene.activeCamera && this._canvas) {
  83639. this._scene.activeCamera.attachControl(this._canvas);
  83640. }
  83641. if (this._interactionsEnabled) {
  83642. this._scene.registerBeforeRender(this.beforeRender);
  83643. }
  83644. };
  83645. /**
  83646. * Attempt to exit VR, or fullscreen.
  83647. */
  83648. VRExperienceHelper.prototype.exitVR = function () {
  83649. if (this.onExitingVRObservable) {
  83650. try {
  83651. this.onExitingVRObservable.notifyObservers(this);
  83652. }
  83653. catch (err) {
  83654. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83655. }
  83656. }
  83657. if (this._webVRpresenting) {
  83658. this._scene.getEngine().disableVR();
  83659. }
  83660. if (this._scene.activeCamera) {
  83661. this._position = this._scene.activeCamera.position.clone();
  83662. }
  83663. if (this._deviceOrientationCamera) {
  83664. this._deviceOrientationCamera.position = this._position;
  83665. this._scene.activeCamera = this._deviceOrientationCamera;
  83666. if (this._canvas) {
  83667. this._scene.activeCamera.attachControl(this._canvas);
  83668. }
  83669. }
  83670. else if (this._existingCamera) {
  83671. this._existingCamera.position = this._position;
  83672. this._scene.activeCamera = this._existingCamera;
  83673. }
  83674. this.updateButtonVisibility();
  83675. if (this._interactionsEnabled) {
  83676. this._scene.unregisterBeforeRender(this.beforeRender);
  83677. }
  83678. };
  83679. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83680. /**
  83681. * The position of the vr experience helper.
  83682. */
  83683. get: function () {
  83684. return this._position;
  83685. },
  83686. /**
  83687. * Sets the position of the vr experience helper.
  83688. */
  83689. set: function (value) {
  83690. this._position = value;
  83691. if (this._scene.activeCamera) {
  83692. this._scene.activeCamera.position = value;
  83693. }
  83694. },
  83695. enumerable: true,
  83696. configurable: true
  83697. });
  83698. /**
  83699. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83700. */
  83701. VRExperienceHelper.prototype.enableInteractions = function () {
  83702. var _this = this;
  83703. if (!this._interactionsEnabled) {
  83704. this._interactionsRequested = true;
  83705. if (this.leftController) {
  83706. this._enableInteractionOnController(this.leftController);
  83707. }
  83708. if (this.rightController) {
  83709. this._enableInteractionOnController(this.rightController);
  83710. }
  83711. this.raySelectionPredicate = function (mesh) {
  83712. return mesh.isVisible;
  83713. };
  83714. this.meshSelectionPredicate = function (mesh) {
  83715. return true;
  83716. };
  83717. this._raySelectionPredicate = function (mesh) {
  83718. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83719. && mesh.name.indexOf("teleportationTarget") === -1
  83720. && mesh.name.indexOf("torusTeleportation") === -1
  83721. && mesh.name.indexOf("laserPointer") === -1)) {
  83722. return _this.raySelectionPredicate(mesh);
  83723. }
  83724. return false;
  83725. };
  83726. this._interactionsEnabled = true;
  83727. }
  83728. };
  83729. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83730. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83731. if (this._floorMeshesCollection[i].id === mesh.id) {
  83732. return true;
  83733. }
  83734. }
  83735. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83736. return true;
  83737. }
  83738. return false;
  83739. };
  83740. /**
  83741. * Adds a floor mesh to be used for teleportation.
  83742. * @param floorMesh the mesh to be used for teleportation.
  83743. */
  83744. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83745. if (!this._floorMeshesCollection) {
  83746. return;
  83747. }
  83748. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83749. return;
  83750. }
  83751. this._floorMeshesCollection.push(floorMesh);
  83752. };
  83753. /**
  83754. * Removes a floor mesh from being used for teleportation.
  83755. * @param floorMesh the mesh to be removed.
  83756. */
  83757. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83758. if (!this._floorMeshesCollection) {
  83759. return;
  83760. }
  83761. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83762. if (meshIndex !== -1) {
  83763. this._floorMeshesCollection.splice(meshIndex, 1);
  83764. }
  83765. };
  83766. /**
  83767. * Enables interactions and teleportation using the VR controllers and gaze.
  83768. * @param vrTeleportationOptions options to modify teleportation behavior.
  83769. */
  83770. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83771. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83772. if (!this._teleportationInitialized) {
  83773. this._teleportationRequested = true;
  83774. this.enableInteractions();
  83775. if (vrTeleportationOptions.floorMeshName) {
  83776. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83777. }
  83778. if (vrTeleportationOptions.floorMeshes) {
  83779. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83780. }
  83781. if (this.leftController != null) {
  83782. this._enableTeleportationOnController(this.leftController);
  83783. }
  83784. if (this.rightController != null) {
  83785. this._enableTeleportationOnController(this.rightController);
  83786. }
  83787. // Creates an image processing post process for the vignette not relying
  83788. // on the main scene configuration for image processing to reduce setup and spaces
  83789. // (gamma/linear) conflicts.
  83790. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83791. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83792. imageProcessingConfiguration.vignetteEnabled = true;
  83793. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83794. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83795. this._teleportationInitialized = true;
  83796. if (this._isDefaultTeleportationTarget) {
  83797. this._createTeleportationCircles();
  83798. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83799. }
  83800. }
  83801. };
  83802. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83803. var _this = this;
  83804. var controllerMesh = controller.webVRController.mesh;
  83805. if (controllerMesh) {
  83806. controller._interactionsEnabled = true;
  83807. controller._activatePointer();
  83808. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83809. // Enabling / disabling laserPointer
  83810. if (_this._displayLaserPointer && stateObject.value === 1) {
  83811. if (controller._activePointer) {
  83812. controller._deactivatePointer();
  83813. }
  83814. else {
  83815. controller._activatePointer();
  83816. }
  83817. if (_this.displayGaze) {
  83818. controller._gazeTracker.isVisible = controller._activePointer;
  83819. }
  83820. }
  83821. });
  83822. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83823. if (!controller._pointerDownOnMeshAsked) {
  83824. if (stateObject.value > _this._padSensibilityUp) {
  83825. controller._selectionPointerDown();
  83826. }
  83827. }
  83828. else if (stateObject.value < _this._padSensibilityDown) {
  83829. controller._selectionPointerUp();
  83830. }
  83831. });
  83832. }
  83833. };
  83834. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83835. // Dont teleport if another gaze already requested teleportation
  83836. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83837. return;
  83838. }
  83839. if (!gazer._teleportationRequestInitiated) {
  83840. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83841. gazer._activatePointer();
  83842. gazer._teleportationRequestInitiated = true;
  83843. }
  83844. }
  83845. else {
  83846. // Listening to the proper controller values changes to confirm teleportation
  83847. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83848. if (this._teleportActive) {
  83849. this._teleportCamera(this._haloCenter);
  83850. }
  83851. gazer._teleportationRequestInitiated = false;
  83852. }
  83853. }
  83854. };
  83855. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83856. // Only rotate when user is not currently selecting a teleportation location
  83857. if (gazer._teleportationRequestInitiated) {
  83858. return;
  83859. }
  83860. if (!this._rotationLeftAsked) {
  83861. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83862. this._rotationLeftAsked = true;
  83863. if (this._rotationAllowed) {
  83864. this._rotateCamera(false);
  83865. }
  83866. }
  83867. }
  83868. else {
  83869. if (stateObject.x > -this._padSensibilityDown) {
  83870. this._rotationLeftAsked = false;
  83871. }
  83872. }
  83873. if (!this._rotationRightAsked) {
  83874. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83875. this._rotationRightAsked = true;
  83876. if (this._rotationAllowed) {
  83877. this._rotateCamera(true);
  83878. }
  83879. }
  83880. }
  83881. else {
  83882. if (stateObject.x < this._padSensibilityDown) {
  83883. this._rotationRightAsked = false;
  83884. }
  83885. }
  83886. };
  83887. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83888. // Only teleport backwards when user is not currently selecting a teleportation location
  83889. if (gazer._teleportationRequestInitiated) {
  83890. return;
  83891. }
  83892. // Teleport backwards
  83893. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83894. if (!gazer._teleportationBackRequestInitiated) {
  83895. if (!this.currentVRCamera) {
  83896. return;
  83897. }
  83898. // Get rotation and position of the current camera
  83899. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83900. var position = this.currentVRCamera.position;
  83901. // If the camera has device position, use that instead
  83902. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83903. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83904. position = this.currentVRCamera.devicePosition;
  83905. }
  83906. // Get matrix with only the y rotation of the device rotation
  83907. rotation.toEulerAnglesToRef(this._workingVector);
  83908. this._workingVector.z = 0;
  83909. this._workingVector.x = 0;
  83910. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83911. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83912. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83913. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83914. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83915. var ray = new BABYLON.Ray(position, this._workingVector);
  83916. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83917. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83918. this._teleportCamera(hit.pickedPoint);
  83919. }
  83920. gazer._teleportationBackRequestInitiated = true;
  83921. }
  83922. }
  83923. else {
  83924. gazer._teleportationBackRequestInitiated = false;
  83925. }
  83926. };
  83927. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83928. var _this = this;
  83929. var controllerMesh = controller.webVRController.mesh;
  83930. if (controllerMesh) {
  83931. if (!controller._interactionsEnabled) {
  83932. this._enableInteractionOnController(controller);
  83933. }
  83934. controller._interactionsEnabled = true;
  83935. controller._teleportationEnabled = true;
  83936. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83937. controller._dpadPressed = false;
  83938. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83939. controller._dpadPressed = stateObject.pressed;
  83940. if (!controller._dpadPressed) {
  83941. _this._rotationLeftAsked = false;
  83942. _this._rotationRightAsked = false;
  83943. controller._teleportationBackRequestInitiated = false;
  83944. }
  83945. });
  83946. }
  83947. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83948. if (_this.teleportationEnabled) {
  83949. _this._checkTeleportBackwards(stateObject, controller);
  83950. _this._checkTeleportWithRay(stateObject, controller);
  83951. }
  83952. _this._checkRotate(stateObject, controller);
  83953. });
  83954. }
  83955. };
  83956. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83957. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83958. this._teleportationTarget.isPickable = false;
  83959. var length = 512;
  83960. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83961. dynamicTexture.hasAlpha = true;
  83962. var context = dynamicTexture.getContext();
  83963. var centerX = length / 2;
  83964. var centerY = length / 2;
  83965. var radius = 200;
  83966. context.beginPath();
  83967. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83968. context.fillStyle = this._teleportationFillColor;
  83969. context.fill();
  83970. context.lineWidth = 10;
  83971. context.strokeStyle = this._teleportationBorderColor;
  83972. context.stroke();
  83973. context.closePath();
  83974. dynamicTexture.update();
  83975. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83976. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83977. this._teleportationTarget.material = teleportationCircleMaterial;
  83978. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83979. torus.isPickable = false;
  83980. torus.parent = this._teleportationTarget;
  83981. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83982. var keys = [];
  83983. keys.push({
  83984. frame: 0,
  83985. value: 0
  83986. });
  83987. keys.push({
  83988. frame: 30,
  83989. value: 0.4
  83990. });
  83991. keys.push({
  83992. frame: 60,
  83993. value: 0
  83994. });
  83995. animationInnerCircle.setKeys(keys);
  83996. var easingFunction = new BABYLON.SineEase();
  83997. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83998. animationInnerCircle.setEasingFunction(easingFunction);
  83999. torus.animations = [];
  84000. torus.animations.push(animationInnerCircle);
  84001. this._scene.beginAnimation(torus, 0, 60, true);
  84002. this._hideTeleportationTarget();
  84003. };
  84004. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  84005. this._teleportActive = true;
  84006. if (this._teleportationInitialized) {
  84007. this._teleportationTarget.isVisible = true;
  84008. if (this._isDefaultTeleportationTarget) {
  84009. this._teleportationTarget.getChildren()[0].isVisible = true;
  84010. }
  84011. }
  84012. };
  84013. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  84014. this._teleportActive = false;
  84015. if (this._teleportationInitialized) {
  84016. this._teleportationTarget.isVisible = false;
  84017. if (this._isDefaultTeleportationTarget) {
  84018. this._teleportationTarget.getChildren()[0].isVisible = false;
  84019. }
  84020. }
  84021. };
  84022. VRExperienceHelper.prototype._rotateCamera = function (right) {
  84023. var _this = this;
  84024. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84025. return;
  84026. }
  84027. if (right) {
  84028. this._rotationAngle++;
  84029. }
  84030. else {
  84031. this._rotationAngle--;
  84032. }
  84033. this.currentVRCamera.animations = [];
  84034. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  84035. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84036. var animationRotationKeys = [];
  84037. animationRotationKeys.push({
  84038. frame: 0,
  84039. value: this.currentVRCamera.rotationQuaternion
  84040. });
  84041. animationRotationKeys.push({
  84042. frame: 6,
  84043. value: target
  84044. });
  84045. animationRotation.setKeys(animationRotationKeys);
  84046. animationRotation.setEasingFunction(this._circleEase);
  84047. this.currentVRCamera.animations.push(animationRotation);
  84048. this._postProcessMove.animations = [];
  84049. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84050. var vignetteWeightKeys = [];
  84051. vignetteWeightKeys.push({
  84052. frame: 0,
  84053. value: 0
  84054. });
  84055. vignetteWeightKeys.push({
  84056. frame: 3,
  84057. value: 4
  84058. });
  84059. vignetteWeightKeys.push({
  84060. frame: 6,
  84061. value: 0
  84062. });
  84063. animationPP.setKeys(vignetteWeightKeys);
  84064. animationPP.setEasingFunction(this._circleEase);
  84065. this._postProcessMove.animations.push(animationPP);
  84066. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84067. var vignetteStretchKeys = [];
  84068. vignetteStretchKeys.push({
  84069. frame: 0,
  84070. value: 0
  84071. });
  84072. vignetteStretchKeys.push({
  84073. frame: 3,
  84074. value: 10
  84075. });
  84076. vignetteStretchKeys.push({
  84077. frame: 6,
  84078. value: 0
  84079. });
  84080. animationPP2.setKeys(vignetteStretchKeys);
  84081. animationPP2.setEasingFunction(this._circleEase);
  84082. this._postProcessMove.animations.push(animationPP2);
  84083. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84084. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84085. this._postProcessMove.samples = 4;
  84086. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84087. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  84088. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84089. });
  84090. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  84091. };
  84092. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  84093. if (hit.pickedPoint) {
  84094. if (gazer._teleportationRequestInitiated) {
  84095. this._displayTeleportationTarget();
  84096. this._haloCenter.copyFrom(hit.pickedPoint);
  84097. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  84098. }
  84099. var pickNormal = hit.getNormal(true, false);
  84100. if (pickNormal) {
  84101. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84102. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84103. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  84104. }
  84105. this._teleportationTarget.position.y += 0.1;
  84106. }
  84107. };
  84108. VRExperienceHelper.prototype._teleportCamera = function (location) {
  84109. var _this = this;
  84110. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84111. return;
  84112. }
  84113. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  84114. // offset of the headset from the anchor.
  84115. if (this.webVRCamera.leftCamera) {
  84116. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  84117. this._workingVector.subtractInPlace(this.webVRCamera.position);
  84118. location.subtractToRef(this._workingVector, this._workingVector);
  84119. }
  84120. else {
  84121. this._workingVector.copyFrom(location);
  84122. }
  84123. // Add height to account for user's height offset
  84124. if (this.isInVRMode) {
  84125. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  84126. }
  84127. else {
  84128. this._workingVector.y += this._defaultHeight;
  84129. }
  84130. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  84131. // Create animation from the camera's position to the new location
  84132. this.currentVRCamera.animations = [];
  84133. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84134. var animationCameraTeleportationKeys = [{
  84135. frame: 0,
  84136. value: this.currentVRCamera.position
  84137. },
  84138. {
  84139. frame: 11,
  84140. value: this._workingVector
  84141. }
  84142. ];
  84143. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  84144. animationCameraTeleportation.setEasingFunction(this._circleEase);
  84145. this.currentVRCamera.animations.push(animationCameraTeleportation);
  84146. this._postProcessMove.animations = [];
  84147. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84148. var vignetteWeightKeys = [];
  84149. vignetteWeightKeys.push({
  84150. frame: 0,
  84151. value: 0
  84152. });
  84153. vignetteWeightKeys.push({
  84154. frame: 5,
  84155. value: 8
  84156. });
  84157. vignetteWeightKeys.push({
  84158. frame: 11,
  84159. value: 0
  84160. });
  84161. animationPP.setKeys(vignetteWeightKeys);
  84162. this._postProcessMove.animations.push(animationPP);
  84163. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  84164. var vignetteStretchKeys = [];
  84165. vignetteStretchKeys.push({
  84166. frame: 0,
  84167. value: 0
  84168. });
  84169. vignetteStretchKeys.push({
  84170. frame: 5,
  84171. value: 10
  84172. });
  84173. vignetteStretchKeys.push({
  84174. frame: 11,
  84175. value: 0
  84176. });
  84177. animationPP2.setKeys(vignetteStretchKeys);
  84178. this._postProcessMove.animations.push(animationPP2);
  84179. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  84180. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  84181. this._webVRCamera.attachPostProcess(this._postProcessMove);
  84182. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  84183. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  84184. });
  84185. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  84186. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  84187. });
  84188. this._hideTeleportationTarget();
  84189. };
  84190. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  84191. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  84192. return;
  84193. }
  84194. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  84195. // Moving the gazeTracker on the mesh face targetted
  84196. if (hit && hit.pickedPoint) {
  84197. if (this._displayGaze) {
  84198. var multiplier = 1;
  84199. gazer._gazeTracker.isVisible = true;
  84200. if (gazer._isActionableMesh) {
  84201. multiplier = 3;
  84202. }
  84203. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  84204. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  84205. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  84206. var pickNormal = hit.getNormal();
  84207. // To avoid z-fighting
  84208. var deltaFighting = 0.002;
  84209. if (pickNormal) {
  84210. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  84211. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  84212. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  84213. }
  84214. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  84215. if (gazer._gazeTracker.position.x < 0) {
  84216. gazer._gazeTracker.position.x += deltaFighting;
  84217. }
  84218. else {
  84219. gazer._gazeTracker.position.x -= deltaFighting;
  84220. }
  84221. if (gazer._gazeTracker.position.y < 0) {
  84222. gazer._gazeTracker.position.y += deltaFighting;
  84223. }
  84224. else {
  84225. gazer._gazeTracker.position.y -= deltaFighting;
  84226. }
  84227. if (gazer._gazeTracker.position.z < 0) {
  84228. gazer._gazeTracker.position.z += deltaFighting;
  84229. }
  84230. else {
  84231. gazer._gazeTracker.position.z -= deltaFighting;
  84232. }
  84233. }
  84234. // Changing the size of the laser pointer based on the distance from the targetted point
  84235. gazer._updatePointerDistance(hit.distance);
  84236. }
  84237. else {
  84238. gazer._gazeTracker.isVisible = false;
  84239. }
  84240. if (hit && hit.pickedMesh) {
  84241. gazer._currentHit = hit;
  84242. if (gazer._pointerDownOnMeshAsked) {
  84243. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  84244. }
  84245. // The object selected is the floor, we're in a teleportation scenario
  84246. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  84247. // Moving the teleportation area to this targetted point
  84248. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  84249. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  84250. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84251. }
  84252. gazer._currentMeshSelected = null;
  84253. if (gazer._teleportationRequestInitiated) {
  84254. this._moveTeleportationSelectorTo(hit, gazer);
  84255. }
  84256. return;
  84257. }
  84258. // If not, we're in a selection scenario
  84259. //this._teleportationAllowed = false;
  84260. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  84261. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  84262. this.onNewMeshPicked.notifyObservers(hit);
  84263. gazer._currentMeshSelected = hit.pickedMesh;
  84264. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  84265. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  84266. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  84267. gazer._isActionableMesh = true;
  84268. }
  84269. else {
  84270. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84271. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84272. gazer._isActionableMesh = false;
  84273. }
  84274. try {
  84275. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  84276. }
  84277. catch (err) {
  84278. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  84279. }
  84280. }
  84281. else {
  84282. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84283. gazer._currentMeshSelected = null;
  84284. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84285. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84286. }
  84287. }
  84288. }
  84289. else {
  84290. gazer._currentHit = null;
  84291. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  84292. gazer._currentMeshSelected = null;
  84293. //this._teleportationAllowed = false;
  84294. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84295. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  84296. }
  84297. };
  84298. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  84299. if (mesh) {
  84300. this.onSelectedMeshUnselected.notifyObservers(mesh);
  84301. }
  84302. };
  84303. /**
  84304. * Sets the color of the laser ray from the vr controllers.
  84305. * @param color new color for the ray.
  84306. */
  84307. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  84308. if (this.leftController) {
  84309. this.leftController._setLaserPointerColor(color);
  84310. }
  84311. if (this.rightController) {
  84312. this.rightController._setLaserPointerColor(color);
  84313. }
  84314. };
  84315. /**
  84316. * Sets the color of the ray from the vr headsets gaze.
  84317. * @param color new color for the ray.
  84318. */
  84319. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  84320. if (!this._cameraGazer._gazeTracker.material) {
  84321. return;
  84322. }
  84323. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  84324. if (this.leftController) {
  84325. this.leftController._gazeTracker.material.emissiveColor = color;
  84326. }
  84327. if (this.rightController) {
  84328. this.rightController._gazeTracker.material.emissiveColor = color;
  84329. }
  84330. };
  84331. /**
  84332. * Exits VR and disposes of the vr experience helper
  84333. */
  84334. VRExperienceHelper.prototype.dispose = function () {
  84335. if (this.isInVRMode) {
  84336. this.exitVR();
  84337. }
  84338. if (this._postProcessMove) {
  84339. this._postProcessMove.dispose();
  84340. }
  84341. if (this._webVRCamera) {
  84342. this._webVRCamera.dispose();
  84343. }
  84344. if (this._vrDeviceOrientationCamera) {
  84345. this._vrDeviceOrientationCamera.dispose();
  84346. }
  84347. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  84348. document.body.removeChild(this._btnVR);
  84349. }
  84350. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  84351. this._deviceOrientationCamera.dispose();
  84352. }
  84353. if (this._cameraGazer) {
  84354. this._cameraGazer.dispose();
  84355. }
  84356. if (this.leftController) {
  84357. this.leftController.dispose();
  84358. }
  84359. if (this.rightController) {
  84360. this.rightController.dispose();
  84361. }
  84362. if (this._teleportationTarget) {
  84363. this._teleportationTarget.dispose();
  84364. }
  84365. this._floorMeshesCollection = [];
  84366. document.removeEventListener("keydown", this._onKeyDown);
  84367. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84368. window.removeEventListener("resize", this._onResize);
  84369. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  84370. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  84371. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  84372. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  84373. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  84374. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  84375. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  84376. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  84377. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  84378. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  84379. this._scene.unregisterBeforeRender(this.beforeRender);
  84380. };
  84381. /**
  84382. * Gets the name of the VRExperienceHelper class
  84383. * @returns "VRExperienceHelper"
  84384. */
  84385. VRExperienceHelper.prototype.getClassName = function () {
  84386. return "VRExperienceHelper";
  84387. };
  84388. return VRExperienceHelper;
  84389. }());
  84390. BABYLON.VRExperienceHelper = VRExperienceHelper;
  84391. })(BABYLON || (BABYLON = {}));
  84392. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  84393. "use strict";
  84394. // Mainly based on these 2 articles :
  84395. // 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
  84396. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  84397. var BABYLON;
  84398. (function (BABYLON) {
  84399. var JoystickAxis;
  84400. (function (JoystickAxis) {
  84401. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  84402. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  84403. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  84404. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  84405. var VirtualJoystick = /** @class */ (function () {
  84406. function VirtualJoystick(leftJoystick) {
  84407. var _this = this;
  84408. if (leftJoystick) {
  84409. this._leftJoystick = true;
  84410. }
  84411. else {
  84412. this._leftJoystick = false;
  84413. }
  84414. VirtualJoystick._globalJoystickIndex++;
  84415. // By default left & right arrow keys are moving the X
  84416. // and up & down keys are moving the Y
  84417. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84418. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84419. this.reverseLeftRight = false;
  84420. this.reverseUpDown = false;
  84421. // collections of pointers
  84422. this._touches = new BABYLON.StringDictionary();
  84423. this.deltaPosition = BABYLON.Vector3.Zero();
  84424. this._joystickSensibility = 25;
  84425. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84426. this._onResize = function (evt) {
  84427. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84428. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84429. if (VirtualJoystick.vjCanvas) {
  84430. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  84431. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  84432. }
  84433. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  84434. };
  84435. // injecting a canvas element on top of the canvas 3D game
  84436. if (!VirtualJoystick.vjCanvas) {
  84437. window.addEventListener("resize", this._onResize, false);
  84438. VirtualJoystick.vjCanvas = document.createElement("canvas");
  84439. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  84440. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  84441. VirtualJoystick.vjCanvas.width = window.innerWidth;
  84442. VirtualJoystick.vjCanvas.height = window.innerHeight;
  84443. VirtualJoystick.vjCanvas.style.width = "100%";
  84444. VirtualJoystick.vjCanvas.style.height = "100%";
  84445. VirtualJoystick.vjCanvas.style.position = "absolute";
  84446. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  84447. VirtualJoystick.vjCanvas.style.top = "0px";
  84448. VirtualJoystick.vjCanvas.style.left = "0px";
  84449. VirtualJoystick.vjCanvas.style.zIndex = "5";
  84450. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  84451. // Support for jQuery PEP polyfill
  84452. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  84453. var context = VirtualJoystick.vjCanvas.getContext('2d');
  84454. if (!context) {
  84455. throw new Error("Unable to create canvas for virtual joystick");
  84456. }
  84457. VirtualJoystick.vjCanvasContext = context;
  84458. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  84459. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84460. document.body.appendChild(VirtualJoystick.vjCanvas);
  84461. }
  84462. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  84463. this.pressed = false;
  84464. // default joystick color
  84465. this._joystickColor = "cyan";
  84466. this._joystickPointerID = -1;
  84467. // current joystick position
  84468. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  84469. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  84470. // origin joystick position
  84471. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  84472. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  84473. this._onPointerDownHandlerRef = function (evt) {
  84474. _this._onPointerDown(evt);
  84475. };
  84476. this._onPointerMoveHandlerRef = function (evt) {
  84477. _this._onPointerMove(evt);
  84478. };
  84479. this._onPointerUpHandlerRef = function (evt) {
  84480. _this._onPointerUp(evt);
  84481. };
  84482. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  84483. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  84484. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  84485. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  84486. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  84487. evt.preventDefault(); // Disables system menu
  84488. }, false);
  84489. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84490. }
  84491. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  84492. this._joystickSensibility = newJoystickSensibility;
  84493. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  84494. };
  84495. VirtualJoystick.prototype._onPointerDown = function (e) {
  84496. var positionOnScreenCondition;
  84497. e.preventDefault();
  84498. if (this._leftJoystick === true) {
  84499. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  84500. }
  84501. else {
  84502. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  84503. }
  84504. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  84505. // First contact will be dedicated to the virtual joystick
  84506. this._joystickPointerID = e.pointerId;
  84507. this._joystickPointerStartPos.x = e.clientX;
  84508. this._joystickPointerStartPos.y = e.clientY;
  84509. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  84510. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  84511. this._deltaJoystickVector.x = 0;
  84512. this._deltaJoystickVector.y = 0;
  84513. this.pressed = true;
  84514. this._touches.add(e.pointerId.toString(), e);
  84515. }
  84516. else {
  84517. // You can only trigger the action buttons with a joystick declared
  84518. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  84519. this._action();
  84520. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  84521. }
  84522. }
  84523. };
  84524. VirtualJoystick.prototype._onPointerMove = function (e) {
  84525. // If the current pointer is the one associated to the joystick (first touch contact)
  84526. if (this._joystickPointerID == e.pointerId) {
  84527. this._joystickPointerPos.x = e.clientX;
  84528. this._joystickPointerPos.y = e.clientY;
  84529. this._deltaJoystickVector = this._joystickPointerPos.clone();
  84530. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  84531. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  84532. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  84533. switch (this._axisTargetedByLeftAndRight) {
  84534. case JoystickAxis.X:
  84535. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  84536. break;
  84537. case JoystickAxis.Y:
  84538. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84539. break;
  84540. case JoystickAxis.Z:
  84541. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84542. break;
  84543. }
  84544. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84545. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84546. switch (this._axisTargetedByUpAndDown) {
  84547. case JoystickAxis.X:
  84548. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84549. break;
  84550. case JoystickAxis.Y:
  84551. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84552. break;
  84553. case JoystickAxis.Z:
  84554. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84555. break;
  84556. }
  84557. }
  84558. else {
  84559. var data = this._touches.get(e.pointerId.toString());
  84560. if (data) {
  84561. data.x = e.clientX;
  84562. data.y = e.clientY;
  84563. }
  84564. }
  84565. };
  84566. VirtualJoystick.prototype._onPointerUp = function (e) {
  84567. if (this._joystickPointerID == e.pointerId) {
  84568. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84569. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84570. this._joystickPointerID = -1;
  84571. this.pressed = false;
  84572. }
  84573. else {
  84574. var touch = this._touches.get(e.pointerId.toString());
  84575. if (touch) {
  84576. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84577. }
  84578. }
  84579. this._deltaJoystickVector.x = 0;
  84580. this._deltaJoystickVector.y = 0;
  84581. this._touches.remove(e.pointerId.toString());
  84582. };
  84583. /**
  84584. * Change the color of the virtual joystick
  84585. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84586. */
  84587. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84588. this._joystickColor = newColor;
  84589. };
  84590. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84591. this._action = action;
  84592. };
  84593. // Define which axis you'd like to control for left & right
  84594. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84595. switch (axis) {
  84596. case JoystickAxis.X:
  84597. case JoystickAxis.Y:
  84598. case JoystickAxis.Z:
  84599. this._axisTargetedByLeftAndRight = axis;
  84600. break;
  84601. default:
  84602. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84603. break;
  84604. }
  84605. };
  84606. // Define which axis you'd like to control for up & down
  84607. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84608. switch (axis) {
  84609. case JoystickAxis.X:
  84610. case JoystickAxis.Y:
  84611. case JoystickAxis.Z:
  84612. this._axisTargetedByUpAndDown = axis;
  84613. break;
  84614. default:
  84615. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84616. break;
  84617. }
  84618. };
  84619. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84620. var _this = this;
  84621. if (this.pressed) {
  84622. this._touches.forEach(function (key, touch) {
  84623. if (touch.pointerId === _this._joystickPointerID) {
  84624. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84625. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84626. VirtualJoystick.vjCanvasContext.beginPath();
  84627. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84628. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84629. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84630. VirtualJoystick.vjCanvasContext.stroke();
  84631. VirtualJoystick.vjCanvasContext.closePath();
  84632. VirtualJoystick.vjCanvasContext.beginPath();
  84633. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84634. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84635. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84636. VirtualJoystick.vjCanvasContext.stroke();
  84637. VirtualJoystick.vjCanvasContext.closePath();
  84638. VirtualJoystick.vjCanvasContext.beginPath();
  84639. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84640. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84641. VirtualJoystick.vjCanvasContext.stroke();
  84642. VirtualJoystick.vjCanvasContext.closePath();
  84643. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84644. }
  84645. else {
  84646. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84647. VirtualJoystick.vjCanvasContext.beginPath();
  84648. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84649. VirtualJoystick.vjCanvasContext.beginPath();
  84650. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84651. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84652. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84653. VirtualJoystick.vjCanvasContext.stroke();
  84654. VirtualJoystick.vjCanvasContext.closePath();
  84655. touch.prevX = touch.x;
  84656. touch.prevY = touch.y;
  84657. }
  84658. ;
  84659. });
  84660. }
  84661. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84662. };
  84663. VirtualJoystick.prototype.releaseCanvas = function () {
  84664. if (VirtualJoystick.vjCanvas) {
  84665. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84666. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84667. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84668. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84669. window.removeEventListener("resize", this._onResize);
  84670. document.body.removeChild(VirtualJoystick.vjCanvas);
  84671. VirtualJoystick.vjCanvas = null;
  84672. }
  84673. };
  84674. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84675. VirtualJoystick._globalJoystickIndex = 0;
  84676. return VirtualJoystick;
  84677. }());
  84678. BABYLON.VirtualJoystick = VirtualJoystick;
  84679. })(BABYLON || (BABYLON = {}));
  84680. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84681. "use strict";
  84682. var BABYLON;
  84683. (function (BABYLON) {
  84684. // We're mainly based on the logic defined into the FreeCamera code
  84685. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84686. __extends(VirtualJoysticksCamera, _super);
  84687. function VirtualJoysticksCamera(name, position, scene) {
  84688. var _this = _super.call(this, name, position, scene) || this;
  84689. _this.inputs.addVirtualJoystick();
  84690. return _this;
  84691. }
  84692. VirtualJoysticksCamera.prototype.getClassName = function () {
  84693. return "VirtualJoysticksCamera";
  84694. };
  84695. return VirtualJoysticksCamera;
  84696. }(BABYLON.FreeCamera));
  84697. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84698. })(BABYLON || (BABYLON = {}));
  84699. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84700. "use strict";
  84701. var BABYLON;
  84702. (function (BABYLON) {
  84703. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84704. function FreeCameraVirtualJoystickInput() {
  84705. }
  84706. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84707. return this._leftjoystick;
  84708. };
  84709. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84710. return this._rightjoystick;
  84711. };
  84712. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84713. if (this._leftjoystick) {
  84714. var camera = this.camera;
  84715. var speed = camera._computeLocalCameraSpeed() * 50;
  84716. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84717. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84718. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84719. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84720. if (!this._leftjoystick.pressed) {
  84721. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84722. }
  84723. if (!this._rightjoystick.pressed) {
  84724. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84725. }
  84726. }
  84727. };
  84728. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84729. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84730. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84731. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84732. this._leftjoystick.setJoystickSensibility(0.15);
  84733. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84734. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84735. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84736. this._rightjoystick.reverseUpDown = true;
  84737. this._rightjoystick.setJoystickSensibility(0.05);
  84738. this._rightjoystick.setJoystickColor("yellow");
  84739. };
  84740. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84741. this._leftjoystick.releaseCanvas();
  84742. this._rightjoystick.releaseCanvas();
  84743. };
  84744. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84745. return "FreeCameraVirtualJoystickInput";
  84746. };
  84747. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84748. return "virtualJoystick";
  84749. };
  84750. return FreeCameraVirtualJoystickInput;
  84751. }());
  84752. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84753. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84754. })(BABYLON || (BABYLON = {}));
  84755. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84756. "use strict";
  84757. var BABYLON;
  84758. (function (BABYLON) {
  84759. var SimplificationSettings = /** @class */ (function () {
  84760. function SimplificationSettings(quality, distance, optimizeMesh) {
  84761. this.quality = quality;
  84762. this.distance = distance;
  84763. this.optimizeMesh = optimizeMesh;
  84764. }
  84765. return SimplificationSettings;
  84766. }());
  84767. BABYLON.SimplificationSettings = SimplificationSettings;
  84768. var SimplificationQueue = /** @class */ (function () {
  84769. function SimplificationQueue() {
  84770. this.running = false;
  84771. this._simplificationArray = [];
  84772. }
  84773. SimplificationQueue.prototype.addTask = function (task) {
  84774. this._simplificationArray.push(task);
  84775. };
  84776. SimplificationQueue.prototype.executeNext = function () {
  84777. var task = this._simplificationArray.pop();
  84778. if (task) {
  84779. this.running = true;
  84780. this.runSimplification(task);
  84781. }
  84782. else {
  84783. this.running = false;
  84784. }
  84785. };
  84786. SimplificationQueue.prototype.runSimplification = function (task) {
  84787. var _this = this;
  84788. if (task.parallelProcessing) {
  84789. //parallel simplifier
  84790. task.settings.forEach(function (setting) {
  84791. var simplifier = _this.getSimplifier(task);
  84792. simplifier.simplify(setting, function (newMesh) {
  84793. task.mesh.addLODLevel(setting.distance, newMesh);
  84794. newMesh.isVisible = true;
  84795. //check if it is the last
  84796. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84797. //all done, run the success callback.
  84798. task.successCallback();
  84799. }
  84800. _this.executeNext();
  84801. });
  84802. });
  84803. }
  84804. else {
  84805. //single simplifier.
  84806. var simplifier = this.getSimplifier(task);
  84807. var runDecimation = function (setting, callback) {
  84808. simplifier.simplify(setting, function (newMesh) {
  84809. task.mesh.addLODLevel(setting.distance, newMesh);
  84810. newMesh.isVisible = true;
  84811. //run the next quality level
  84812. callback();
  84813. });
  84814. };
  84815. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84816. runDecimation(task.settings[loop.index], function () {
  84817. loop.executeNext();
  84818. });
  84819. }, function () {
  84820. //execution ended, run the success callback.
  84821. if (task.successCallback) {
  84822. task.successCallback();
  84823. }
  84824. _this.executeNext();
  84825. });
  84826. }
  84827. };
  84828. SimplificationQueue.prototype.getSimplifier = function (task) {
  84829. switch (task.simplificationType) {
  84830. case SimplificationType.QUADRATIC:
  84831. default:
  84832. return new QuadraticErrorSimplification(task.mesh);
  84833. }
  84834. };
  84835. return SimplificationQueue;
  84836. }());
  84837. BABYLON.SimplificationQueue = SimplificationQueue;
  84838. /**
  84839. * The implemented types of simplification.
  84840. * At the moment only Quadratic Error Decimation is implemented.
  84841. */
  84842. var SimplificationType;
  84843. (function (SimplificationType) {
  84844. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84845. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84846. var DecimationTriangle = /** @class */ (function () {
  84847. function DecimationTriangle(vertices) {
  84848. this.vertices = vertices;
  84849. this.error = new Array(4);
  84850. this.deleted = false;
  84851. this.isDirty = false;
  84852. this.deletePending = false;
  84853. this.borderFactor = 0;
  84854. }
  84855. return DecimationTriangle;
  84856. }());
  84857. BABYLON.DecimationTriangle = DecimationTriangle;
  84858. var DecimationVertex = /** @class */ (function () {
  84859. function DecimationVertex(position, id) {
  84860. this.position = position;
  84861. this.id = id;
  84862. this.isBorder = true;
  84863. this.q = new QuadraticMatrix();
  84864. this.triangleCount = 0;
  84865. this.triangleStart = 0;
  84866. this.originalOffsets = [];
  84867. }
  84868. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84869. this.position.copyFrom(newPosition);
  84870. };
  84871. return DecimationVertex;
  84872. }());
  84873. BABYLON.DecimationVertex = DecimationVertex;
  84874. var QuadraticMatrix = /** @class */ (function () {
  84875. function QuadraticMatrix(data) {
  84876. this.data = new Array(10);
  84877. for (var i = 0; i < 10; ++i) {
  84878. if (data && data[i]) {
  84879. this.data[i] = data[i];
  84880. }
  84881. else {
  84882. this.data[i] = 0;
  84883. }
  84884. }
  84885. }
  84886. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84887. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84888. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84889. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84890. return det;
  84891. };
  84892. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84893. for (var i = 0; i < 10; ++i) {
  84894. this.data[i] += matrix.data[i];
  84895. }
  84896. };
  84897. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84898. for (var i = 0; i < 10; ++i) {
  84899. this.data[i] += data[i];
  84900. }
  84901. };
  84902. QuadraticMatrix.prototype.add = function (matrix) {
  84903. var m = new QuadraticMatrix();
  84904. for (var i = 0; i < 10; ++i) {
  84905. m.data[i] = this.data[i] + matrix.data[i];
  84906. }
  84907. return m;
  84908. };
  84909. QuadraticMatrix.FromData = function (a, b, c, d) {
  84910. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84911. };
  84912. //returning an array to avoid garbage collection
  84913. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84914. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84915. };
  84916. return QuadraticMatrix;
  84917. }());
  84918. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84919. var Reference = /** @class */ (function () {
  84920. function Reference(vertexId, triangleId) {
  84921. this.vertexId = vertexId;
  84922. this.triangleId = triangleId;
  84923. }
  84924. return Reference;
  84925. }());
  84926. BABYLON.Reference = Reference;
  84927. /**
  84928. * An implementation of the Quadratic Error simplification algorithm.
  84929. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84930. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84931. * @author RaananW
  84932. */
  84933. var QuadraticErrorSimplification = /** @class */ (function () {
  84934. function QuadraticErrorSimplification(_mesh) {
  84935. this._mesh = _mesh;
  84936. this.syncIterations = 5000;
  84937. this.aggressiveness = 7;
  84938. this.decimationIterations = 100;
  84939. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84940. }
  84941. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84942. var _this = this;
  84943. this.initDecimatedMesh();
  84944. //iterating through the submeshes array, one after the other.
  84945. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84946. _this.initWithMesh(loop.index, function () {
  84947. _this.runDecimation(settings, loop.index, function () {
  84948. loop.executeNext();
  84949. });
  84950. }, settings.optimizeMesh);
  84951. }, function () {
  84952. setTimeout(function () {
  84953. successCallback(_this._reconstructedMesh);
  84954. }, 0);
  84955. });
  84956. };
  84957. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84958. var _this = this;
  84959. var targetCount = ~~(this.triangles.length * settings.quality);
  84960. var deletedTriangles = 0;
  84961. var triangleCount = this.triangles.length;
  84962. var iterationFunction = function (iteration, callback) {
  84963. setTimeout(function () {
  84964. if (iteration % 5 === 0) {
  84965. _this.updateMesh(iteration === 0);
  84966. }
  84967. for (var i = 0; i < _this.triangles.length; ++i) {
  84968. _this.triangles[i].isDirty = false;
  84969. }
  84970. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84971. var trianglesIterator = function (i) {
  84972. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84973. var t = _this.triangles[tIdx];
  84974. if (!t)
  84975. return;
  84976. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84977. return;
  84978. }
  84979. for (var j = 0; j < 3; ++j) {
  84980. if (t.error[j] < threshold) {
  84981. var deleted0 = [];
  84982. var deleted1 = [];
  84983. var v0 = t.vertices[j];
  84984. var v1 = t.vertices[(j + 1) % 3];
  84985. if (v0.isBorder || v1.isBorder)
  84986. continue;
  84987. var p = BABYLON.Vector3.Zero();
  84988. var n = BABYLON.Vector3.Zero();
  84989. var uv = BABYLON.Vector2.Zero();
  84990. var color = new BABYLON.Color4(0, 0, 0, 1);
  84991. _this.calculateError(v0, v1, p, n, uv, color);
  84992. var delTr = new Array();
  84993. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84994. continue;
  84995. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84996. continue;
  84997. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84998. continue;
  84999. var uniqueArray = new Array();
  85000. delTr.forEach(function (deletedT) {
  85001. if (uniqueArray.indexOf(deletedT) === -1) {
  85002. deletedT.deletePending = true;
  85003. uniqueArray.push(deletedT);
  85004. }
  85005. });
  85006. if (uniqueArray.length % 2 !== 0) {
  85007. continue;
  85008. }
  85009. v0.q = v1.q.add(v0.q);
  85010. v0.updatePosition(p);
  85011. var tStart = _this.references.length;
  85012. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  85013. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  85014. var tCount = _this.references.length - tStart;
  85015. if (tCount <= v0.triangleCount) {
  85016. if (tCount) {
  85017. for (var c = 0; c < tCount; c++) {
  85018. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  85019. }
  85020. }
  85021. }
  85022. else {
  85023. v0.triangleStart = tStart;
  85024. }
  85025. v0.triangleCount = tCount;
  85026. break;
  85027. }
  85028. }
  85029. };
  85030. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  85031. }, 0);
  85032. };
  85033. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  85034. if (triangleCount - deletedTriangles <= targetCount)
  85035. loop.breakLoop();
  85036. else {
  85037. iterationFunction(loop.index, function () {
  85038. loop.executeNext();
  85039. });
  85040. }
  85041. }, function () {
  85042. setTimeout(function () {
  85043. //reconstruct this part of the mesh
  85044. _this.reconstructMesh(submeshIndex);
  85045. successCallback();
  85046. }, 0);
  85047. });
  85048. };
  85049. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  85050. var _this = this;
  85051. this.vertices = [];
  85052. this.triangles = [];
  85053. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85054. var indices = this._mesh.getIndices();
  85055. var submesh = this._mesh.subMeshes[submeshIndex];
  85056. var findInVertices = function (positionToSearch) {
  85057. if (optimizeMesh) {
  85058. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  85059. if (_this.vertices[ii].position.equals(positionToSearch)) {
  85060. return _this.vertices[ii];
  85061. }
  85062. }
  85063. }
  85064. return null;
  85065. };
  85066. var vertexReferences = [];
  85067. var vertexInit = function (i) {
  85068. if (!positionData) {
  85069. return;
  85070. }
  85071. var offset = i + submesh.verticesStart;
  85072. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  85073. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  85074. vertex.originalOffsets.push(offset);
  85075. if (vertex.id === _this.vertices.length) {
  85076. _this.vertices.push(vertex);
  85077. }
  85078. vertexReferences.push(vertex.id);
  85079. };
  85080. //var totalVertices = mesh.getTotalVertices();
  85081. var totalVertices = submesh.verticesCount;
  85082. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  85083. var indicesInit = function (i) {
  85084. if (!indices) {
  85085. return;
  85086. }
  85087. var offset = (submesh.indexStart / 3) + i;
  85088. var pos = (offset * 3);
  85089. var i0 = indices[pos + 0];
  85090. var i1 = indices[pos + 1];
  85091. var i2 = indices[pos + 2];
  85092. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  85093. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  85094. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  85095. var triangle = new DecimationTriangle([v0, v1, v2]);
  85096. triangle.originalOffset = pos;
  85097. _this.triangles.push(triangle);
  85098. };
  85099. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  85100. _this.init(callback);
  85101. });
  85102. });
  85103. };
  85104. QuadraticErrorSimplification.prototype.init = function (callback) {
  85105. var _this = this;
  85106. var triangleInit1 = function (i) {
  85107. var t = _this.triangles[i];
  85108. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  85109. for (var j = 0; j < 3; j++) {
  85110. 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))));
  85111. }
  85112. };
  85113. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  85114. var triangleInit2 = function (i) {
  85115. var t = _this.triangles[i];
  85116. for (var j = 0; j < 3; ++j) {
  85117. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  85118. }
  85119. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85120. };
  85121. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  85122. callback();
  85123. });
  85124. });
  85125. };
  85126. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  85127. var newTriangles = [];
  85128. var i;
  85129. for (i = 0; i < this.vertices.length; ++i) {
  85130. this.vertices[i].triangleCount = 0;
  85131. }
  85132. var t;
  85133. var j;
  85134. for (i = 0; i < this.triangles.length; ++i) {
  85135. if (!this.triangles[i].deleted) {
  85136. t = this.triangles[i];
  85137. for (j = 0; j < 3; ++j) {
  85138. t.vertices[j].triangleCount = 1;
  85139. }
  85140. newTriangles.push(t);
  85141. }
  85142. }
  85143. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  85144. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  85145. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  85146. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  85147. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  85148. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85149. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  85150. var vertexCount = 0;
  85151. for (i = 0; i < this.vertices.length; ++i) {
  85152. var vertex = this.vertices[i];
  85153. vertex.id = vertexCount;
  85154. if (vertex.triangleCount) {
  85155. vertex.originalOffsets.forEach(function (originalOffset) {
  85156. if (!normalData) {
  85157. return;
  85158. }
  85159. newPositionData.push(vertex.position.x);
  85160. newPositionData.push(vertex.position.y);
  85161. newPositionData.push(vertex.position.z);
  85162. newNormalData.push(normalData[originalOffset * 3]);
  85163. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  85164. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  85165. if (uvs && uvs.length) {
  85166. newUVsData.push(uvs[(originalOffset * 2)]);
  85167. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  85168. }
  85169. else if (colorsData && colorsData.length) {
  85170. newColorsData.push(colorsData[(originalOffset * 4)]);
  85171. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  85172. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  85173. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  85174. }
  85175. ++vertexCount;
  85176. });
  85177. }
  85178. }
  85179. var startingIndex = this._reconstructedMesh.getTotalIndices();
  85180. var startingVertex = this._reconstructedMesh.getTotalVertices();
  85181. var submeshesArray = this._reconstructedMesh.subMeshes;
  85182. this._reconstructedMesh.subMeshes = [];
  85183. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  85184. var originalIndices = this._mesh.getIndices();
  85185. for (i = 0; i < newTriangles.length; ++i) {
  85186. t = newTriangles[i]; //now get the new referencing point for each vertex
  85187. [0, 1, 2].forEach(function (idx) {
  85188. var id = originalIndices[t.originalOffset + idx];
  85189. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  85190. if (offset < 0)
  85191. offset = 0;
  85192. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  85193. });
  85194. }
  85195. //overwriting the old vertex buffers and indices.
  85196. this._reconstructedMesh.setIndices(newIndicesArray);
  85197. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  85198. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  85199. if (newUVsData.length > 0)
  85200. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  85201. if (newColorsData.length > 0)
  85202. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  85203. //create submesh
  85204. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  85205. if (submeshIndex > 0) {
  85206. this._reconstructedMesh.subMeshes = [];
  85207. submeshesArray.forEach(function (submesh) {
  85208. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  85209. });
  85210. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  85211. }
  85212. };
  85213. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  85214. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  85215. this._reconstructedMesh.material = this._mesh.material;
  85216. this._reconstructedMesh.parent = this._mesh.parent;
  85217. this._reconstructedMesh.isVisible = false;
  85218. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  85219. };
  85220. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  85221. for (var i = 0; i < vertex1.triangleCount; ++i) {
  85222. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  85223. if (t.deleted)
  85224. continue;
  85225. var s = this.references[vertex1.triangleStart + i].vertexId;
  85226. var v1 = t.vertices[(s + 1) % 3];
  85227. var v2 = t.vertices[(s + 2) % 3];
  85228. if ((v1 === vertex2 || v2 === vertex2)) {
  85229. deletedArray[i] = true;
  85230. delTr.push(t);
  85231. continue;
  85232. }
  85233. var d1 = v1.position.subtract(point);
  85234. d1 = d1.normalize();
  85235. var d2 = v2.position.subtract(point);
  85236. d2 = d2.normalize();
  85237. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  85238. return true;
  85239. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  85240. deletedArray[i] = false;
  85241. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  85242. return true;
  85243. }
  85244. return false;
  85245. };
  85246. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  85247. var newDeleted = deletedTriangles;
  85248. for (var i = 0; i < vertex.triangleCount; ++i) {
  85249. var ref = this.references[vertex.triangleStart + i];
  85250. var t = this.triangles[ref.triangleId];
  85251. if (t.deleted)
  85252. continue;
  85253. if (deletedArray[i] && t.deletePending) {
  85254. t.deleted = true;
  85255. newDeleted++;
  85256. continue;
  85257. }
  85258. t.vertices[ref.vertexId] = origVertex;
  85259. t.isDirty = true;
  85260. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  85261. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  85262. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  85263. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  85264. this.references.push(ref);
  85265. }
  85266. return newDeleted;
  85267. };
  85268. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  85269. for (var i = 0; i < this.vertices.length; ++i) {
  85270. var vCount = [];
  85271. var vId = [];
  85272. var v = this.vertices[i];
  85273. var j;
  85274. for (j = 0; j < v.triangleCount; ++j) {
  85275. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  85276. for (var ii = 0; ii < 3; ii++) {
  85277. var ofs = 0;
  85278. var vv = triangle.vertices[ii];
  85279. while (ofs < vCount.length) {
  85280. if (vId[ofs] === vv.id)
  85281. break;
  85282. ++ofs;
  85283. }
  85284. if (ofs === vCount.length) {
  85285. vCount.push(1);
  85286. vId.push(vv.id);
  85287. }
  85288. else {
  85289. vCount[ofs]++;
  85290. }
  85291. }
  85292. }
  85293. for (j = 0; j < vCount.length; ++j) {
  85294. if (vCount[j] === 1) {
  85295. this.vertices[vId[j]].isBorder = true;
  85296. }
  85297. else {
  85298. this.vertices[vId[j]].isBorder = false;
  85299. }
  85300. }
  85301. }
  85302. };
  85303. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  85304. if (identifyBorders === void 0) { identifyBorders = false; }
  85305. var i;
  85306. if (!identifyBorders) {
  85307. var newTrianglesVector = [];
  85308. for (i = 0; i < this.triangles.length; ++i) {
  85309. if (!this.triangles[i].deleted) {
  85310. newTrianglesVector.push(this.triangles[i]);
  85311. }
  85312. }
  85313. this.triangles = newTrianglesVector;
  85314. }
  85315. for (i = 0; i < this.vertices.length; ++i) {
  85316. this.vertices[i].triangleCount = 0;
  85317. this.vertices[i].triangleStart = 0;
  85318. }
  85319. var t;
  85320. var j;
  85321. var v;
  85322. for (i = 0; i < this.triangles.length; ++i) {
  85323. t = this.triangles[i];
  85324. for (j = 0; j < 3; ++j) {
  85325. v = t.vertices[j];
  85326. v.triangleCount++;
  85327. }
  85328. }
  85329. var tStart = 0;
  85330. for (i = 0; i < this.vertices.length; ++i) {
  85331. this.vertices[i].triangleStart = tStart;
  85332. tStart += this.vertices[i].triangleCount;
  85333. this.vertices[i].triangleCount = 0;
  85334. }
  85335. var newReferences = new Array(this.triangles.length * 3);
  85336. for (i = 0; i < this.triangles.length; ++i) {
  85337. t = this.triangles[i];
  85338. for (j = 0; j < 3; ++j) {
  85339. v = t.vertices[j];
  85340. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  85341. v.triangleCount++;
  85342. }
  85343. }
  85344. this.references = newReferences;
  85345. if (identifyBorders) {
  85346. this.identifyBorder();
  85347. }
  85348. };
  85349. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  85350. var x = point.x;
  85351. var y = point.y;
  85352. var z = point.z;
  85353. 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
  85354. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  85355. };
  85356. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  85357. var q = vertex1.q.add(vertex2.q);
  85358. var border = vertex1.isBorder && vertex2.isBorder;
  85359. var error = 0;
  85360. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  85361. if (qDet !== 0 && !border) {
  85362. if (!pointResult) {
  85363. pointResult = BABYLON.Vector3.Zero();
  85364. }
  85365. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  85366. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  85367. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  85368. error = this.vertexError(q, pointResult);
  85369. }
  85370. else {
  85371. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  85372. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  85373. var error1 = this.vertexError(q, vertex1.position);
  85374. var error2 = this.vertexError(q, vertex2.position);
  85375. var error3 = this.vertexError(q, p3);
  85376. error = Math.min(error1, error2, error3);
  85377. if (error === error1) {
  85378. if (pointResult) {
  85379. pointResult.copyFrom(vertex1.position);
  85380. }
  85381. }
  85382. else if (error === error2) {
  85383. if (pointResult) {
  85384. pointResult.copyFrom(vertex2.position);
  85385. }
  85386. }
  85387. else {
  85388. if (pointResult) {
  85389. pointResult.copyFrom(p3);
  85390. }
  85391. }
  85392. }
  85393. return error;
  85394. };
  85395. return QuadraticErrorSimplification;
  85396. }());
  85397. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  85398. })(BABYLON || (BABYLON = {}));
  85399. //# sourceMappingURL=babylon.meshSimplification.js.map
  85400. "use strict";
  85401. var BABYLON;
  85402. (function (BABYLON) {
  85403. var MeshLODLevel = /** @class */ (function () {
  85404. function MeshLODLevel(distance, mesh) {
  85405. this.distance = distance;
  85406. this.mesh = mesh;
  85407. }
  85408. return MeshLODLevel;
  85409. }());
  85410. BABYLON.MeshLODLevel = MeshLODLevel;
  85411. })(BABYLON || (BABYLON = {}));
  85412. //# sourceMappingURL=babylon.meshLODLevel.js.map
  85413. "use strict";
  85414. var BABYLON;
  85415. (function (BABYLON) {
  85416. /**
  85417. * Defines the root class used to create scene optimization to use with SceneOptimizer
  85418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85419. */
  85420. var SceneOptimization = /** @class */ (function () {
  85421. /**
  85422. * Creates the SceneOptimization object
  85423. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85424. * @param desc defines the description associated with the optimization
  85425. */
  85426. function SceneOptimization(
  85427. /**
  85428. * Defines the priority of this optimization (0 by default which means first in the list)
  85429. */
  85430. priority) {
  85431. if (priority === void 0) { priority = 0; }
  85432. this.priority = priority;
  85433. }
  85434. /**
  85435. * Gets a string describing the action executed by the current optimization
  85436. * @returns description string
  85437. */
  85438. SceneOptimization.prototype.getDescription = function () {
  85439. return "";
  85440. };
  85441. /**
  85442. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85443. * @param scene defines the current scene where to apply this optimization
  85444. * @param optimizer defines the current optimizer
  85445. * @returns true if everything that can be done was applied
  85446. */
  85447. SceneOptimization.prototype.apply = function (scene, optimizer) {
  85448. return true;
  85449. };
  85450. ;
  85451. return SceneOptimization;
  85452. }());
  85453. BABYLON.SceneOptimization = SceneOptimization;
  85454. /**
  85455. * Defines an optimization used to reduce the size of render target textures
  85456. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85457. */
  85458. var TextureOptimization = /** @class */ (function (_super) {
  85459. __extends(TextureOptimization, _super);
  85460. /**
  85461. * Creates the TextureOptimization object
  85462. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85463. * @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
  85464. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85465. */
  85466. function TextureOptimization(
  85467. /**
  85468. * Defines the priority of this optimization (0 by default which means first in the list)
  85469. */
  85470. priority,
  85471. /**
  85472. * 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
  85473. */
  85474. maximumSize,
  85475. /**
  85476. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  85477. */
  85478. step) {
  85479. if (priority === void 0) { priority = 0; }
  85480. if (maximumSize === void 0) { maximumSize = 1024; }
  85481. if (step === void 0) { step = 0.5; }
  85482. var _this = _super.call(this, priority) || this;
  85483. _this.priority = priority;
  85484. _this.maximumSize = maximumSize;
  85485. _this.step = step;
  85486. return _this;
  85487. }
  85488. /**
  85489. * Gets a string describing the action executed by the current optimization
  85490. * @returns description string
  85491. */
  85492. TextureOptimization.prototype.getDescription = function () {
  85493. return "Reducing render target texture size to " + this.maximumSize;
  85494. };
  85495. /**
  85496. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85497. * @param scene defines the current scene where to apply this optimization
  85498. * @param optimizer defines the current optimizer
  85499. * @returns true if everything that can be done was applied
  85500. */
  85501. TextureOptimization.prototype.apply = function (scene, optimizer) {
  85502. var allDone = true;
  85503. for (var index = 0; index < scene.textures.length; index++) {
  85504. var texture = scene.textures[index];
  85505. if (!texture.canRescale || texture.getContext) {
  85506. continue;
  85507. }
  85508. var currentSize = texture.getSize();
  85509. var maxDimension = Math.max(currentSize.width, currentSize.height);
  85510. if (maxDimension > this.maximumSize) {
  85511. texture.scale(this.step);
  85512. allDone = false;
  85513. }
  85514. }
  85515. return allDone;
  85516. };
  85517. return TextureOptimization;
  85518. }(SceneOptimization));
  85519. BABYLON.TextureOptimization = TextureOptimization;
  85520. /**
  85521. * Defines an optimization used to increase or decrease the rendering resolution
  85522. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85523. */
  85524. var HardwareScalingOptimization = /** @class */ (function (_super) {
  85525. __extends(HardwareScalingOptimization, _super);
  85526. /**
  85527. * Creates the HardwareScalingOptimization object
  85528. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85529. * @param maximumScale defines the maximum scale to use (2 by default)
  85530. * @param step defines the step to use between two passes (0.5 by default)
  85531. */
  85532. function HardwareScalingOptimization(
  85533. /**
  85534. * Defines the priority of this optimization (0 by default which means first in the list)
  85535. */
  85536. priority,
  85537. /**
  85538. * Defines the maximum scale to use (2 by default)
  85539. */
  85540. maximumScale,
  85541. /**
  85542. * Defines the step to use between two passes (0.5 by default)
  85543. */
  85544. step) {
  85545. if (priority === void 0) { priority = 0; }
  85546. if (maximumScale === void 0) { maximumScale = 2; }
  85547. if (step === void 0) { step = 0.25; }
  85548. var _this = _super.call(this, priority) || this;
  85549. _this.priority = priority;
  85550. _this.maximumScale = maximumScale;
  85551. _this.step = step;
  85552. _this._currentScale = -1;
  85553. _this._directionOffset = 1;
  85554. return _this;
  85555. }
  85556. /**
  85557. * Gets a string describing the action executed by the current optimization
  85558. * @return description string
  85559. */
  85560. HardwareScalingOptimization.prototype.getDescription = function () {
  85561. return "Setting hardware scaling level to " + this._currentScale;
  85562. };
  85563. /**
  85564. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85565. * @param scene defines the current scene where to apply this optimization
  85566. * @param optimizer defines the current optimizer
  85567. * @returns true if everything that can be done was applied
  85568. */
  85569. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85570. if (this._currentScale === -1) {
  85571. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85572. if (this._currentScale > this.maximumScale) {
  85573. this._directionOffset = -1;
  85574. }
  85575. }
  85576. this._currentScale += this._directionOffset * this.step;
  85577. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85578. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85579. };
  85580. ;
  85581. return HardwareScalingOptimization;
  85582. }(SceneOptimization));
  85583. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85584. /**
  85585. * Defines an optimization used to remove shadows
  85586. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85587. */
  85588. var ShadowsOptimization = /** @class */ (function (_super) {
  85589. __extends(ShadowsOptimization, _super);
  85590. function ShadowsOptimization() {
  85591. return _super !== null && _super.apply(this, arguments) || this;
  85592. }
  85593. /**
  85594. * Gets a string describing the action executed by the current optimization
  85595. * @return description string
  85596. */
  85597. ShadowsOptimization.prototype.getDescription = function () {
  85598. return "Turning shadows on/off";
  85599. };
  85600. /**
  85601. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85602. * @param scene defines the current scene where to apply this optimization
  85603. * @param optimizer defines the current optimizer
  85604. * @returns true if everything that can be done was applied
  85605. */
  85606. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85607. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85608. return true;
  85609. };
  85610. ;
  85611. return ShadowsOptimization;
  85612. }(SceneOptimization));
  85613. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85614. /**
  85615. * Defines an optimization used to turn post-processes off
  85616. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85617. */
  85618. var PostProcessesOptimization = /** @class */ (function (_super) {
  85619. __extends(PostProcessesOptimization, _super);
  85620. function PostProcessesOptimization() {
  85621. return _super !== null && _super.apply(this, arguments) || this;
  85622. }
  85623. /**
  85624. * Gets a string describing the action executed by the current optimization
  85625. * @return description string
  85626. */
  85627. PostProcessesOptimization.prototype.getDescription = function () {
  85628. return "Turning post-processes on/off";
  85629. };
  85630. /**
  85631. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85632. * @param scene defines the current scene where to apply this optimization
  85633. * @param optimizer defines the current optimizer
  85634. * @returns true if everything that can be done was applied
  85635. */
  85636. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85637. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85638. return true;
  85639. };
  85640. ;
  85641. return PostProcessesOptimization;
  85642. }(SceneOptimization));
  85643. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85644. /**
  85645. * Defines an optimization used to turn lens flares off
  85646. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85647. */
  85648. var LensFlaresOptimization = /** @class */ (function (_super) {
  85649. __extends(LensFlaresOptimization, _super);
  85650. function LensFlaresOptimization() {
  85651. return _super !== null && _super.apply(this, arguments) || this;
  85652. }
  85653. /**
  85654. * Gets a string describing the action executed by the current optimization
  85655. * @return description string
  85656. */
  85657. LensFlaresOptimization.prototype.getDescription = function () {
  85658. return "Turning lens flares on/off";
  85659. };
  85660. /**
  85661. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85662. * @param scene defines the current scene where to apply this optimization
  85663. * @param optimizer defines the current optimizer
  85664. * @returns true if everything that can be done was applied
  85665. */
  85666. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85667. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85668. return true;
  85669. };
  85670. ;
  85671. return LensFlaresOptimization;
  85672. }(SceneOptimization));
  85673. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85674. /**
  85675. * Defines an optimization based on user defined callback.
  85676. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85677. */
  85678. var CustomOptimization = /** @class */ (function (_super) {
  85679. __extends(CustomOptimization, _super);
  85680. function CustomOptimization() {
  85681. return _super !== null && _super.apply(this, arguments) || this;
  85682. }
  85683. /**
  85684. * Gets a string describing the action executed by the current optimization
  85685. * @returns description string
  85686. */
  85687. CustomOptimization.prototype.getDescription = function () {
  85688. if (this.onGetDescription) {
  85689. return this.onGetDescription();
  85690. }
  85691. return "Running user defined callback";
  85692. };
  85693. /**
  85694. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85695. * @param scene defines the current scene where to apply this optimization
  85696. * @param optimizer defines the current optimizer
  85697. * @returns true if everything that can be done was applied
  85698. */
  85699. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85700. if (this.onApply) {
  85701. return this.onApply(scene, optimizer);
  85702. }
  85703. return true;
  85704. };
  85705. ;
  85706. return CustomOptimization;
  85707. }(SceneOptimization));
  85708. BABYLON.CustomOptimization = CustomOptimization;
  85709. /**
  85710. * Defines an optimization used to turn particles off
  85711. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85712. */
  85713. var ParticlesOptimization = /** @class */ (function (_super) {
  85714. __extends(ParticlesOptimization, _super);
  85715. function ParticlesOptimization() {
  85716. return _super !== null && _super.apply(this, arguments) || this;
  85717. }
  85718. /**
  85719. * Gets a string describing the action executed by the current optimization
  85720. * @return description string
  85721. */
  85722. ParticlesOptimization.prototype.getDescription = function () {
  85723. return "Turning particles on/off";
  85724. };
  85725. /**
  85726. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85727. * @param scene defines the current scene where to apply this optimization
  85728. * @param optimizer defines the current optimizer
  85729. * @returns true if everything that can be done was applied
  85730. */
  85731. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85732. scene.particlesEnabled = optimizer.isInImprovementMode;
  85733. return true;
  85734. };
  85735. ;
  85736. return ParticlesOptimization;
  85737. }(SceneOptimization));
  85738. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85739. /**
  85740. * Defines an optimization used to turn render targets off
  85741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85742. */
  85743. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85744. __extends(RenderTargetsOptimization, _super);
  85745. function RenderTargetsOptimization() {
  85746. return _super !== null && _super.apply(this, arguments) || this;
  85747. }
  85748. /**
  85749. * Gets a string describing the action executed by the current optimization
  85750. * @return description string
  85751. */
  85752. RenderTargetsOptimization.prototype.getDescription = function () {
  85753. return "Turning render targets off";
  85754. };
  85755. /**
  85756. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85757. * @param scene defines the current scene where to apply this optimization
  85758. * @param optimizer defines the current optimizer
  85759. * @returns true if everything that can be done was applied
  85760. */
  85761. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85762. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85763. return true;
  85764. };
  85765. ;
  85766. return RenderTargetsOptimization;
  85767. }(SceneOptimization));
  85768. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85769. /**
  85770. * Defines an optimization used to merge meshes with compatible materials
  85771. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85772. */
  85773. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85774. __extends(MergeMeshesOptimization, _super);
  85775. function MergeMeshesOptimization() {
  85776. var _this = _super !== null && _super.apply(this, arguments) || this;
  85777. _this._canBeMerged = function (abstractMesh) {
  85778. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85779. return false;
  85780. }
  85781. var mesh = abstractMesh;
  85782. if (!mesh.isVisible || !mesh.isEnabled()) {
  85783. return false;
  85784. }
  85785. if (mesh.instances.length > 0) {
  85786. return false;
  85787. }
  85788. if (mesh.skeleton || mesh.hasLODLevels) {
  85789. return false;
  85790. }
  85791. if (mesh.parent) {
  85792. return false;
  85793. }
  85794. return true;
  85795. };
  85796. return _this;
  85797. }
  85798. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85799. /**
  85800. * Gets or sets a boolean which defines if optimization octree has to be updated
  85801. */
  85802. get: function () {
  85803. return MergeMeshesOptimization._UpdateSelectionTree;
  85804. },
  85805. /**
  85806. * Gets or sets a boolean which defines if optimization octree has to be updated
  85807. */
  85808. set: function (value) {
  85809. MergeMeshesOptimization._UpdateSelectionTree = value;
  85810. },
  85811. enumerable: true,
  85812. configurable: true
  85813. });
  85814. /**
  85815. * Gets a string describing the action executed by the current optimization
  85816. * @return description string
  85817. */
  85818. MergeMeshesOptimization.prototype.getDescription = function () {
  85819. return "Merging similar meshes together";
  85820. };
  85821. /**
  85822. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85823. * @param scene defines the current scene where to apply this optimization
  85824. * @param optimizer defines the current optimizer
  85825. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85826. * @returns true if everything that can be done was applied
  85827. */
  85828. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85829. var globalPool = scene.meshes.slice(0);
  85830. var globalLength = globalPool.length;
  85831. for (var index = 0; index < globalLength; index++) {
  85832. var currentPool = new Array();
  85833. var current = globalPool[index];
  85834. // Checks
  85835. if (!this._canBeMerged(current)) {
  85836. continue;
  85837. }
  85838. currentPool.push(current);
  85839. // Find compatible meshes
  85840. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85841. var otherMesh = globalPool[subIndex];
  85842. if (!this._canBeMerged(otherMesh)) {
  85843. continue;
  85844. }
  85845. if (otherMesh.material !== current.material) {
  85846. continue;
  85847. }
  85848. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85849. continue;
  85850. }
  85851. currentPool.push(otherMesh);
  85852. globalLength--;
  85853. globalPool.splice(subIndex, 1);
  85854. subIndex--;
  85855. }
  85856. if (currentPool.length < 2) {
  85857. continue;
  85858. }
  85859. // Merge meshes
  85860. BABYLON.Mesh.MergeMeshes(currentPool);
  85861. }
  85862. if (updateSelectionTree != undefined) {
  85863. if (updateSelectionTree) {
  85864. scene.createOrUpdateSelectionOctree();
  85865. }
  85866. }
  85867. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85868. scene.createOrUpdateSelectionOctree();
  85869. }
  85870. return true;
  85871. };
  85872. ;
  85873. MergeMeshesOptimization._UpdateSelectionTree = false;
  85874. return MergeMeshesOptimization;
  85875. }(SceneOptimization));
  85876. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85877. /**
  85878. * Defines a list of options used by SceneOptimizer
  85879. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85880. */
  85881. var SceneOptimizerOptions = /** @class */ (function () {
  85882. /**
  85883. * Creates a new list of options used by SceneOptimizer
  85884. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85885. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85886. */
  85887. function SceneOptimizerOptions(
  85888. /**
  85889. * Defines the target frame rate to reach (60 by default)
  85890. */
  85891. targetFrameRate,
  85892. /**
  85893. * Defines the interval between two checkes (2000ms by default)
  85894. */
  85895. trackerDuration) {
  85896. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85897. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85898. this.targetFrameRate = targetFrameRate;
  85899. this.trackerDuration = trackerDuration;
  85900. /**
  85901. * Gets the list of optimizations to apply
  85902. */
  85903. this.optimizations = new Array();
  85904. }
  85905. /**
  85906. * Add a new optimization
  85907. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85908. * @returns the current SceneOptimizerOptions
  85909. */
  85910. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85911. this.optimizations.push(optimization);
  85912. return this;
  85913. };
  85914. /**
  85915. * Add a new custom optimization
  85916. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85917. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85918. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85919. * @returns the current SceneOptimizerOptions
  85920. */
  85921. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85922. if (priority === void 0) { priority = 0; }
  85923. var optimization = new CustomOptimization(priority);
  85924. optimization.onApply = onApply;
  85925. optimization.onGetDescription = onGetDescription;
  85926. this.optimizations.push(optimization);
  85927. return this;
  85928. };
  85929. /**
  85930. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85931. * @param targetFrameRate defines the target frame rate (60 by default)
  85932. * @returns a SceneOptimizerOptions object
  85933. */
  85934. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85935. var result = new SceneOptimizerOptions(targetFrameRate);
  85936. var priority = 0;
  85937. result.addOptimization(new MergeMeshesOptimization(priority));
  85938. result.addOptimization(new ShadowsOptimization(priority));
  85939. result.addOptimization(new LensFlaresOptimization(priority));
  85940. // Next priority
  85941. priority++;
  85942. result.addOptimization(new PostProcessesOptimization(priority));
  85943. result.addOptimization(new ParticlesOptimization(priority));
  85944. // Next priority
  85945. priority++;
  85946. result.addOptimization(new TextureOptimization(priority, 1024));
  85947. return result;
  85948. };
  85949. /**
  85950. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85951. * @param targetFrameRate defines the target frame rate (60 by default)
  85952. * @returns a SceneOptimizerOptions object
  85953. */
  85954. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85955. var result = new SceneOptimizerOptions(targetFrameRate);
  85956. var priority = 0;
  85957. result.addOptimization(new MergeMeshesOptimization(priority));
  85958. result.addOptimization(new ShadowsOptimization(priority));
  85959. result.addOptimization(new LensFlaresOptimization(priority));
  85960. // Next priority
  85961. priority++;
  85962. result.addOptimization(new PostProcessesOptimization(priority));
  85963. result.addOptimization(new ParticlesOptimization(priority));
  85964. // Next priority
  85965. priority++;
  85966. result.addOptimization(new TextureOptimization(priority, 512));
  85967. // Next priority
  85968. priority++;
  85969. result.addOptimization(new RenderTargetsOptimization(priority));
  85970. // Next priority
  85971. priority++;
  85972. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85973. return result;
  85974. };
  85975. /**
  85976. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85977. * @param targetFrameRate defines the target frame rate (60 by default)
  85978. * @returns a SceneOptimizerOptions object
  85979. */
  85980. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85981. var result = new SceneOptimizerOptions(targetFrameRate);
  85982. var priority = 0;
  85983. result.addOptimization(new MergeMeshesOptimization(priority));
  85984. result.addOptimization(new ShadowsOptimization(priority));
  85985. result.addOptimization(new LensFlaresOptimization(priority));
  85986. // Next priority
  85987. priority++;
  85988. result.addOptimization(new PostProcessesOptimization(priority));
  85989. result.addOptimization(new ParticlesOptimization(priority));
  85990. // Next priority
  85991. priority++;
  85992. result.addOptimization(new TextureOptimization(priority, 256));
  85993. // Next priority
  85994. priority++;
  85995. result.addOptimization(new RenderTargetsOptimization(priority));
  85996. // Next priority
  85997. priority++;
  85998. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85999. return result;
  86000. };
  86001. return SceneOptimizerOptions;
  86002. }());
  86003. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  86004. /**
  86005. * Class used to run optimizations in order to reach a target frame rate
  86006. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  86007. */
  86008. var SceneOptimizer = /** @class */ (function () {
  86009. /**
  86010. * Creates a new SceneOptimizer
  86011. * @param scene defines the scene to work on
  86012. * @param options defines the options to use with the SceneOptimizer
  86013. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  86014. * @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)
  86015. */
  86016. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  86017. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  86018. if (improvementMode === void 0) { improvementMode = false; }
  86019. var _this = this;
  86020. this._isRunning = false;
  86021. this._currentPriorityLevel = 0;
  86022. this._targetFrameRate = 60;
  86023. this._trackerDuration = 2000;
  86024. this._currentFrameRate = 0;
  86025. this._improvementMode = false;
  86026. /**
  86027. * Defines an observable called when the optimizer reaches the target frame rate
  86028. */
  86029. this.onSuccessObservable = new BABYLON.Observable();
  86030. /**
  86031. * Defines an observable called when the optimizer enables an optimization
  86032. */
  86033. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  86034. /**
  86035. * Defines an observable called when the optimizer is not able to reach the target frame rate
  86036. */
  86037. this.onFailureObservable = new BABYLON.Observable();
  86038. if (!options) {
  86039. this._options = new SceneOptimizerOptions();
  86040. }
  86041. else {
  86042. this._options = options;
  86043. }
  86044. if (this._options.targetFrameRate) {
  86045. this._targetFrameRate = this._options.targetFrameRate;
  86046. }
  86047. if (this._options.trackerDuration) {
  86048. this._trackerDuration = this._options.trackerDuration;
  86049. }
  86050. if (autoGeneratePriorities) {
  86051. var priority = 0;
  86052. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  86053. var optim = _a[_i];
  86054. optim.priority = priority++;
  86055. }
  86056. }
  86057. this._improvementMode = improvementMode;
  86058. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86059. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  86060. _this._sceneDisposeObserver = null;
  86061. _this.dispose();
  86062. });
  86063. }
  86064. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  86065. /**
  86066. * Gets a boolean indicating if the optimizer is in improvement mode
  86067. */
  86068. get: function () {
  86069. return this._improvementMode;
  86070. },
  86071. enumerable: true,
  86072. configurable: true
  86073. });
  86074. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  86075. /**
  86076. * Gets the current priority level (0 at start)
  86077. */
  86078. get: function () {
  86079. return this._currentPriorityLevel;
  86080. },
  86081. enumerable: true,
  86082. configurable: true
  86083. });
  86084. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  86085. /**
  86086. * Gets the current frame rate checked by the SceneOptimizer
  86087. */
  86088. get: function () {
  86089. return this._currentFrameRate;
  86090. },
  86091. enumerable: true,
  86092. configurable: true
  86093. });
  86094. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  86095. /**
  86096. * Gets or sets the current target frame rate (60 by default)
  86097. */
  86098. get: function () {
  86099. return this._targetFrameRate;
  86100. },
  86101. /**
  86102. * Gets or sets the current target frame rate (60 by default)
  86103. */
  86104. set: function (value) {
  86105. this._targetFrameRate = value;
  86106. },
  86107. enumerable: true,
  86108. configurable: true
  86109. });
  86110. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  86111. /**
  86112. * Gets or sets the current interval between two checks (every 2000ms by default)
  86113. */
  86114. get: function () {
  86115. return this._trackerDuration;
  86116. },
  86117. /**
  86118. * Gets or sets the current interval between two checks (every 2000ms by default)
  86119. */
  86120. set: function (value) {
  86121. this._trackerDuration = value;
  86122. },
  86123. enumerable: true,
  86124. configurable: true
  86125. });
  86126. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  86127. /**
  86128. * Gets the list of active optimizations
  86129. */
  86130. get: function () {
  86131. return this._options.optimizations;
  86132. },
  86133. enumerable: true,
  86134. configurable: true
  86135. });
  86136. /**
  86137. * Stops the current optimizer
  86138. */
  86139. SceneOptimizer.prototype.stop = function () {
  86140. this._isRunning = false;
  86141. };
  86142. /**
  86143. * Reset the optimizer to initial step (current priority level = 0)
  86144. */
  86145. SceneOptimizer.prototype.reset = function () {
  86146. this._currentPriorityLevel = 0;
  86147. };
  86148. /**
  86149. * Start the optimizer. By default it will try to reach a specific framerate
  86150. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  86151. */
  86152. SceneOptimizer.prototype.start = function () {
  86153. var _this = this;
  86154. if (this._isRunning) {
  86155. return;
  86156. }
  86157. this._isRunning = true;
  86158. // Let's wait for the scene to be ready before running our check
  86159. this._scene.executeWhenReady(function () {
  86160. setTimeout(function () {
  86161. _this._checkCurrentState();
  86162. }, _this._trackerDuration);
  86163. });
  86164. };
  86165. SceneOptimizer.prototype._checkCurrentState = function () {
  86166. var _this = this;
  86167. if (!this._isRunning) {
  86168. return;
  86169. }
  86170. var scene = this._scene;
  86171. var options = this._options;
  86172. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  86173. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  86174. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  86175. this._isRunning = false;
  86176. this.onSuccessObservable.notifyObservers(this);
  86177. return;
  86178. }
  86179. // Apply current level of optimizations
  86180. var allDone = true;
  86181. var noOptimizationApplied = true;
  86182. for (var index = 0; index < options.optimizations.length; index++) {
  86183. var optimization = options.optimizations[index];
  86184. if (optimization.priority === this._currentPriorityLevel) {
  86185. noOptimizationApplied = false;
  86186. allDone = allDone && optimization.apply(scene, this);
  86187. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  86188. }
  86189. }
  86190. // If no optimization was applied, this is a failure :(
  86191. if (noOptimizationApplied) {
  86192. this._isRunning = false;
  86193. this.onFailureObservable.notifyObservers(this);
  86194. return;
  86195. }
  86196. // If all optimizations were done, move to next level
  86197. if (allDone) {
  86198. this._currentPriorityLevel++;
  86199. }
  86200. // Let's the system running for a specific amount of time before checking FPS
  86201. scene.executeWhenReady(function () {
  86202. setTimeout(function () {
  86203. _this._checkCurrentState();
  86204. }, _this._trackerDuration);
  86205. });
  86206. };
  86207. /**
  86208. * Release all resources
  86209. */
  86210. SceneOptimizer.prototype.dispose = function () {
  86211. this.stop();
  86212. this.onSuccessObservable.clear();
  86213. this.onFailureObservable.clear();
  86214. this.onNewOptimizationAppliedObservable.clear();
  86215. if (this._sceneDisposeObserver) {
  86216. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  86217. }
  86218. };
  86219. /**
  86220. * Helper function to create a SceneOptimizer with one single line of code
  86221. * @param scene defines the scene to work on
  86222. * @param options defines the options to use with the SceneOptimizer
  86223. * @param onSuccess defines a callback to call on success
  86224. * @param onFailure defines a callback to call on failure
  86225. * @returns the new SceneOptimizer object
  86226. */
  86227. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  86228. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  86229. if (onSuccess) {
  86230. optimizer.onSuccessObservable.add(function () {
  86231. onSuccess();
  86232. });
  86233. }
  86234. if (onFailure) {
  86235. optimizer.onFailureObservable.add(function () {
  86236. onFailure();
  86237. });
  86238. }
  86239. optimizer.start();
  86240. return optimizer;
  86241. };
  86242. return SceneOptimizer;
  86243. }());
  86244. BABYLON.SceneOptimizer = SceneOptimizer;
  86245. })(BABYLON || (BABYLON = {}));
  86246. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  86247. "use strict";
  86248. var BABYLON;
  86249. (function (BABYLON) {
  86250. var OutlineRenderer = /** @class */ (function () {
  86251. function OutlineRenderer(scene) {
  86252. this.zOffset = 1;
  86253. this._scene = scene;
  86254. }
  86255. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  86256. var _this = this;
  86257. if (useOverlay === void 0) { useOverlay = false; }
  86258. var scene = this._scene;
  86259. var engine = this._scene.getEngine();
  86260. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86261. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  86262. return;
  86263. }
  86264. var mesh = subMesh.getRenderingMesh();
  86265. var material = subMesh.getMaterial();
  86266. if (!material || !scene.activeCamera) {
  86267. return;
  86268. }
  86269. engine.enableEffect(this._effect);
  86270. // Logarithmic depth
  86271. if (material.useLogarithmicDepth) {
  86272. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  86273. }
  86274. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  86275. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  86276. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  86277. // Bones
  86278. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86279. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86280. }
  86281. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  86282. // Alpha test
  86283. if (material && material.needAlphaTesting()) {
  86284. var alphaTexture = material.getAlphaTestTexture();
  86285. if (alphaTexture) {
  86286. this._effect.setTexture("diffuseSampler", alphaTexture);
  86287. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  86288. }
  86289. }
  86290. engine.setZOffset(-this.zOffset);
  86291. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  86292. engine.setZOffset(0);
  86293. };
  86294. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  86295. var defines = [];
  86296. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  86297. var mesh = subMesh.getMesh();
  86298. var material = subMesh.getMaterial();
  86299. if (material) {
  86300. // Alpha test
  86301. if (material.needAlphaTesting()) {
  86302. defines.push("#define ALPHATEST");
  86303. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86304. attribs.push(BABYLON.VertexBuffer.UVKind);
  86305. defines.push("#define UV1");
  86306. }
  86307. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  86308. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86309. defines.push("#define UV2");
  86310. }
  86311. }
  86312. //Logarithmic depth
  86313. if (material.useLogarithmicDepth) {
  86314. defines.push("#define LOGARITHMICDEPTH");
  86315. }
  86316. }
  86317. // Bones
  86318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86321. if (mesh.numBoneInfluencers > 4) {
  86322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86324. }
  86325. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86326. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  86327. }
  86328. else {
  86329. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86330. }
  86331. // Instances
  86332. if (useInstances) {
  86333. defines.push("#define INSTANCES");
  86334. attribs.push("world0");
  86335. attribs.push("world1");
  86336. attribs.push("world2");
  86337. attribs.push("world3");
  86338. }
  86339. // Get correct effect
  86340. var join = defines.join("\n");
  86341. if (this._cachedDefines !== join) {
  86342. this._cachedDefines = join;
  86343. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  86344. }
  86345. return this._effect.isReady();
  86346. };
  86347. return OutlineRenderer;
  86348. }());
  86349. BABYLON.OutlineRenderer = OutlineRenderer;
  86350. })(BABYLON || (BABYLON = {}));
  86351. //# sourceMappingURL=babylon.outlineRenderer.js.map
  86352. "use strict";
  86353. var BABYLON;
  86354. (function (BABYLON) {
  86355. var FaceAdjacencies = /** @class */ (function () {
  86356. function FaceAdjacencies() {
  86357. this.edges = new Array();
  86358. this.edgesConnectedCount = 0;
  86359. }
  86360. return FaceAdjacencies;
  86361. }());
  86362. var EdgesRenderer = /** @class */ (function () {
  86363. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  86364. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  86365. if (epsilon === void 0) { epsilon = 0.95; }
  86366. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  86367. this.edgesWidthScalerForOrthographic = 1000.0;
  86368. this.edgesWidthScalerForPerspective = 50.0;
  86369. this._linesPositions = new Array();
  86370. this._linesNormals = new Array();
  86371. this._linesIndices = new Array();
  86372. this._buffers = {};
  86373. this._checkVerticesInsteadOfIndices = false;
  86374. this._source = source;
  86375. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  86376. this._epsilon = epsilon;
  86377. this._prepareRessources();
  86378. this._generateEdgesLines();
  86379. }
  86380. EdgesRenderer.prototype._prepareRessources = function () {
  86381. if (this._lineShader) {
  86382. return;
  86383. }
  86384. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  86385. attributes: ["position", "normal"],
  86386. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  86387. });
  86388. this._lineShader.disableDepthWrite = true;
  86389. this._lineShader.backFaceCulling = false;
  86390. };
  86391. EdgesRenderer.prototype._rebuild = function () {
  86392. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86393. if (buffer) {
  86394. buffer._rebuild();
  86395. }
  86396. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86397. if (buffer) {
  86398. buffer._rebuild();
  86399. }
  86400. var scene = this._source.getScene();
  86401. var engine = scene.getEngine();
  86402. this._ib = engine.createIndexBuffer(this._linesIndices);
  86403. };
  86404. EdgesRenderer.prototype.dispose = function () {
  86405. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  86406. if (buffer) {
  86407. buffer.dispose();
  86408. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  86409. }
  86410. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  86411. if (buffer) {
  86412. buffer.dispose();
  86413. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  86414. }
  86415. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  86416. this._lineShader.dispose();
  86417. };
  86418. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  86419. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  86420. return 0;
  86421. }
  86422. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  86423. return 1;
  86424. }
  86425. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  86426. return 2;
  86427. }
  86428. return -1;
  86429. };
  86430. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  86431. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  86432. return 0;
  86433. }
  86434. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  86435. return 1;
  86436. }
  86437. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  86438. return 2;
  86439. }
  86440. return -1;
  86441. };
  86442. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  86443. var needToCreateLine;
  86444. if (edge === undefined) {
  86445. needToCreateLine = true;
  86446. }
  86447. else {
  86448. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  86449. needToCreateLine = dotProduct < this._epsilon;
  86450. }
  86451. if (needToCreateLine) {
  86452. var offset = this._linesPositions.length / 3;
  86453. var normal = p0.subtract(p1);
  86454. normal.normalize();
  86455. // Positions
  86456. this._linesPositions.push(p0.x);
  86457. this._linesPositions.push(p0.y);
  86458. this._linesPositions.push(p0.z);
  86459. this._linesPositions.push(p0.x);
  86460. this._linesPositions.push(p0.y);
  86461. this._linesPositions.push(p0.z);
  86462. this._linesPositions.push(p1.x);
  86463. this._linesPositions.push(p1.y);
  86464. this._linesPositions.push(p1.z);
  86465. this._linesPositions.push(p1.x);
  86466. this._linesPositions.push(p1.y);
  86467. this._linesPositions.push(p1.z);
  86468. // Normals
  86469. this._linesNormals.push(p1.x);
  86470. this._linesNormals.push(p1.y);
  86471. this._linesNormals.push(p1.z);
  86472. this._linesNormals.push(-1);
  86473. this._linesNormals.push(p1.x);
  86474. this._linesNormals.push(p1.y);
  86475. this._linesNormals.push(p1.z);
  86476. this._linesNormals.push(1);
  86477. this._linesNormals.push(p0.x);
  86478. this._linesNormals.push(p0.y);
  86479. this._linesNormals.push(p0.z);
  86480. this._linesNormals.push(-1);
  86481. this._linesNormals.push(p0.x);
  86482. this._linesNormals.push(p0.y);
  86483. this._linesNormals.push(p0.z);
  86484. this._linesNormals.push(1);
  86485. // Indices
  86486. this._linesIndices.push(offset);
  86487. this._linesIndices.push(offset + 1);
  86488. this._linesIndices.push(offset + 2);
  86489. this._linesIndices.push(offset);
  86490. this._linesIndices.push(offset + 2);
  86491. this._linesIndices.push(offset + 3);
  86492. }
  86493. };
  86494. EdgesRenderer.prototype._generateEdgesLines = function () {
  86495. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  86496. var indices = this._source.getIndices();
  86497. if (!indices || !positions) {
  86498. return;
  86499. }
  86500. // First let's find adjacencies
  86501. var adjacencies = new Array();
  86502. var faceNormals = new Array();
  86503. var index;
  86504. var faceAdjacencies;
  86505. // Prepare faces
  86506. for (index = 0; index < indices.length; index += 3) {
  86507. faceAdjacencies = new FaceAdjacencies();
  86508. var p0Index = indices[index];
  86509. var p1Index = indices[index + 1];
  86510. var p2Index = indices[index + 2];
  86511. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  86512. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  86513. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  86514. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  86515. faceNormal.normalize();
  86516. faceNormals.push(faceNormal);
  86517. adjacencies.push(faceAdjacencies);
  86518. }
  86519. // Scan
  86520. for (index = 0; index < adjacencies.length; index++) {
  86521. faceAdjacencies = adjacencies[index];
  86522. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  86523. var otherFaceAdjacencies = adjacencies[otherIndex];
  86524. if (faceAdjacencies.edgesConnectedCount === 3) {
  86525. break;
  86526. }
  86527. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  86528. continue;
  86529. }
  86530. var otherP0 = indices[otherIndex * 3];
  86531. var otherP1 = indices[otherIndex * 3 + 1];
  86532. var otherP2 = indices[otherIndex * 3 + 2];
  86533. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  86534. var otherEdgeIndex = 0;
  86535. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  86536. continue;
  86537. }
  86538. switch (edgeIndex) {
  86539. case 0:
  86540. if (this._checkVerticesInsteadOfIndices) {
  86541. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86542. }
  86543. else {
  86544. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86545. }
  86546. break;
  86547. case 1:
  86548. if (this._checkVerticesInsteadOfIndices) {
  86549. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86550. }
  86551. else {
  86552. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86553. }
  86554. break;
  86555. case 2:
  86556. if (this._checkVerticesInsteadOfIndices) {
  86557. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86558. }
  86559. else {
  86560. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86561. }
  86562. break;
  86563. }
  86564. if (otherEdgeIndex === -1) {
  86565. continue;
  86566. }
  86567. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86568. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86569. faceAdjacencies.edgesConnectedCount++;
  86570. otherFaceAdjacencies.edgesConnectedCount++;
  86571. if (faceAdjacencies.edgesConnectedCount === 3) {
  86572. break;
  86573. }
  86574. }
  86575. }
  86576. }
  86577. // Create lines
  86578. for (index = 0; index < adjacencies.length; index++) {
  86579. // 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
  86580. var current = adjacencies[index];
  86581. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86582. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86583. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86584. }
  86585. // Merge into a single mesh
  86586. var engine = this._source.getScene().getEngine();
  86587. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86588. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86589. this._ib = engine.createIndexBuffer(this._linesIndices);
  86590. this._indicesCount = this._linesIndices.length;
  86591. };
  86592. EdgesRenderer.prototype.render = function () {
  86593. var scene = this._source.getScene();
  86594. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86595. return;
  86596. }
  86597. var engine = scene.getEngine();
  86598. this._lineShader._preBind();
  86599. // VBOs
  86600. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86601. scene.resetCachedMaterial();
  86602. this._lineShader.setColor4("color", this._source.edgesColor);
  86603. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86604. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86605. }
  86606. else {
  86607. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86608. }
  86609. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86610. this._lineShader.bind(this._source.getWorldMatrix());
  86611. // Draw order
  86612. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86613. this._lineShader.unbind();
  86614. engine.setDepthWrite(true);
  86615. };
  86616. return EdgesRenderer;
  86617. }());
  86618. BABYLON.EdgesRenderer = EdgesRenderer;
  86619. })(BABYLON || (BABYLON = {}));
  86620. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86621. "use strict";
  86622. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86623. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86624. s = arguments[i];
  86625. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86626. t[p] = s[p];
  86627. }
  86628. return t;
  86629. };
  86630. var BABYLON;
  86631. (function (BABYLON) {
  86632. /**
  86633. * The effect layer Helps adding post process effect blended with the main pass.
  86634. *
  86635. * This can be for instance use to generate glow or higlight effects on the scene.
  86636. *
  86637. * The effect layer class can not be used directly and is intented to inherited from to be
  86638. * customized per effects.
  86639. */
  86640. var EffectLayer = /** @class */ (function () {
  86641. /**
  86642. * Instantiates a new effect Layer and references it in the scene.
  86643. * @param name The name of the layer
  86644. * @param scene The scene to use the layer in
  86645. */
  86646. function EffectLayer(
  86647. /** The Friendly of the effect in the scene */
  86648. name, scene) {
  86649. this.name = name;
  86650. this._vertexBuffers = {};
  86651. this._maxSize = 0;
  86652. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86653. this._shouldRender = true;
  86654. this._postProcesses = [];
  86655. this._textures = [];
  86656. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86657. /**
  86658. * The clear color of the texture used to generate the glow map.
  86659. */
  86660. this.neutralColor = new BABYLON.Color4();
  86661. /**
  86662. * Specifies wether the highlight layer is enabled or not.
  86663. */
  86664. this.isEnabled = true;
  86665. /**
  86666. * An event triggered when the effect layer has been disposed.
  86667. */
  86668. this.onDisposeObservable = new BABYLON.Observable();
  86669. /**
  86670. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86671. */
  86672. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86673. /**
  86674. * An event triggered when the generated texture is being merged in the scene.
  86675. */
  86676. this.onBeforeComposeObservable = new BABYLON.Observable();
  86677. /**
  86678. * An event triggered when the generated texture has been merged in the scene.
  86679. */
  86680. this.onAfterComposeObservable = new BABYLON.Observable();
  86681. /**
  86682. * An event triggered when the efffect layer changes its size.
  86683. */
  86684. this.onSizeChangedObservable = new BABYLON.Observable();
  86685. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86686. this._engine = scene.getEngine();
  86687. this._maxSize = this._engine.getCaps().maxTextureSize;
  86688. this._scene.effectLayers.push(this);
  86689. // Generate Buffers
  86690. this._generateIndexBuffer();
  86691. this._genrateVertexBuffer();
  86692. }
  86693. Object.defineProperty(EffectLayer.prototype, "camera", {
  86694. /**
  86695. * Gets the camera attached to the layer.
  86696. */
  86697. get: function () {
  86698. return this._effectLayerOptions.camera;
  86699. },
  86700. enumerable: true,
  86701. configurable: true
  86702. });
  86703. /**
  86704. * Initializes the effect layer with the required options.
  86705. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86706. */
  86707. EffectLayer.prototype._init = function (options) {
  86708. // Adapt options
  86709. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86710. this._setMainTextureSize();
  86711. this._createMainTexture();
  86712. this._createTextureAndPostProcesses();
  86713. this._mergeEffect = this._createMergeEffect();
  86714. };
  86715. /**
  86716. * Generates the index buffer of the full screen quad blending to the main canvas.
  86717. */
  86718. EffectLayer.prototype._generateIndexBuffer = function () {
  86719. // Indices
  86720. var indices = [];
  86721. indices.push(0);
  86722. indices.push(1);
  86723. indices.push(2);
  86724. indices.push(0);
  86725. indices.push(2);
  86726. indices.push(3);
  86727. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86728. };
  86729. /**
  86730. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86731. */
  86732. EffectLayer.prototype._genrateVertexBuffer = function () {
  86733. // VBO
  86734. var vertices = [];
  86735. vertices.push(1, 1);
  86736. vertices.push(-1, 1);
  86737. vertices.push(-1, -1);
  86738. vertices.push(1, -1);
  86739. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86740. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86741. };
  86742. /**
  86743. * Sets the main texture desired size which is the closest power of two
  86744. * of the engine canvas size.
  86745. */
  86746. EffectLayer.prototype._setMainTextureSize = function () {
  86747. if (this._effectLayerOptions.mainTextureFixedSize) {
  86748. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86749. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86750. }
  86751. else {
  86752. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86753. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86754. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86755. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86756. }
  86757. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86758. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86759. };
  86760. /**
  86761. * Creates the main texture for the effect layer.
  86762. */
  86763. EffectLayer.prototype._createMainTexture = function () {
  86764. var _this = this;
  86765. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86766. width: this._mainTextureDesiredSize.width,
  86767. height: this._mainTextureDesiredSize.height
  86768. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86769. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86770. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86771. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86772. this._mainTexture.anisotropicFilteringLevel = 1;
  86773. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86774. this._mainTexture.renderParticles = false;
  86775. this._mainTexture.renderList = null;
  86776. this._mainTexture.ignoreCameraViewport = true;
  86777. // Custom render function
  86778. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86779. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86780. var index;
  86781. var engine = _this._scene.getEngine();
  86782. if (depthOnlySubMeshes.length) {
  86783. engine.setColorWrite(false);
  86784. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86785. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86786. }
  86787. engine.setColorWrite(true);
  86788. }
  86789. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86790. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86791. }
  86792. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86793. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86794. }
  86795. for (index = 0; index < transparentSubMeshes.length; index++) {
  86796. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86797. }
  86798. };
  86799. this._mainTexture.onClearObservable.add(function (engine) {
  86800. engine.clear(_this.neutralColor, true, true, true);
  86801. });
  86802. };
  86803. /**
  86804. * Checks for the readiness of the element composing the layer.
  86805. * @param subMesh the mesh to check for
  86806. * @param useInstances specify wether or not to use instances to render the mesh
  86807. * @param emissiveTexture the associated emissive texture used to generate the glow
  86808. * @return true if ready otherwise, false
  86809. */
  86810. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86811. var material = subMesh.getMaterial();
  86812. if (!material) {
  86813. return false;
  86814. }
  86815. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86816. return false;
  86817. }
  86818. var defines = [];
  86819. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86820. var mesh = subMesh.getMesh();
  86821. var uv1 = false;
  86822. var uv2 = false;
  86823. // Alpha test
  86824. if (material && material.needAlphaTesting()) {
  86825. var alphaTexture = material.getAlphaTestTexture();
  86826. if (alphaTexture) {
  86827. defines.push("#define ALPHATEST");
  86828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86829. alphaTexture.coordinatesIndex === 1) {
  86830. defines.push("#define DIFFUSEUV2");
  86831. uv2 = true;
  86832. }
  86833. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86834. defines.push("#define DIFFUSEUV1");
  86835. uv1 = true;
  86836. }
  86837. }
  86838. }
  86839. // Emissive
  86840. if (emissiveTexture) {
  86841. defines.push("#define EMISSIVE");
  86842. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86843. emissiveTexture.coordinatesIndex === 1) {
  86844. defines.push("#define EMISSIVEUV2");
  86845. uv2 = true;
  86846. }
  86847. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86848. defines.push("#define EMISSIVEUV1");
  86849. uv1 = true;
  86850. }
  86851. }
  86852. if (uv1) {
  86853. attribs.push(BABYLON.VertexBuffer.UVKind);
  86854. defines.push("#define UV1");
  86855. }
  86856. if (uv2) {
  86857. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86858. defines.push("#define UV2");
  86859. }
  86860. // Bones
  86861. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86862. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86863. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86864. if (mesh.numBoneInfluencers > 4) {
  86865. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86866. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86867. }
  86868. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86869. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86870. }
  86871. else {
  86872. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86873. }
  86874. // Morph targets
  86875. var manager = mesh.morphTargetManager;
  86876. var morphInfluencers = 0;
  86877. if (manager) {
  86878. if (manager.numInfluencers > 0) {
  86879. defines.push("#define MORPHTARGETS");
  86880. morphInfluencers = manager.numInfluencers;
  86881. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  86882. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  86883. }
  86884. }
  86885. // Instances
  86886. if (useInstances) {
  86887. defines.push("#define INSTANCES");
  86888. attribs.push("world0");
  86889. attribs.push("world1");
  86890. attribs.push("world2");
  86891. attribs.push("world3");
  86892. }
  86893. // Get correct effect
  86894. var join = defines.join("\n");
  86895. if (this._cachedDefines !== join) {
  86896. this._cachedDefines = join;
  86897. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  86898. }
  86899. return this._effectLayerMapGenerationEffect.isReady();
  86900. };
  86901. /**
  86902. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86903. */
  86904. EffectLayer.prototype.render = function () {
  86905. var currentEffect = this._mergeEffect;
  86906. // Check
  86907. if (!currentEffect.isReady())
  86908. return;
  86909. for (var i = 0; i < this._postProcesses.length; i++) {
  86910. if (!this._postProcesses[i].isReady()) {
  86911. return;
  86912. }
  86913. }
  86914. var engine = this._scene.getEngine();
  86915. this.onBeforeComposeObservable.notifyObservers(this);
  86916. // Render
  86917. engine.enableEffect(currentEffect);
  86918. engine.setState(false);
  86919. // VBOs
  86920. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86921. // Cache
  86922. var previousAlphaMode = engine.getAlphaMode();
  86923. // Go Blend.
  86924. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86925. // Blends the map on the main canvas.
  86926. this._internalRender(currentEffect);
  86927. // Restore Alpha
  86928. engine.setAlphaMode(previousAlphaMode);
  86929. this.onAfterComposeObservable.notifyObservers(this);
  86930. // Handle size changes.
  86931. var size = this._mainTexture.getSize();
  86932. this._setMainTextureSize();
  86933. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86934. // Recreate RTT and post processes on size change.
  86935. this.onSizeChangedObservable.notifyObservers(this);
  86936. this._disposeTextureAndPostProcesses();
  86937. this._createMainTexture();
  86938. this._createTextureAndPostProcesses();
  86939. }
  86940. };
  86941. /**
  86942. * Determine if a given mesh will be used in the current effect.
  86943. * @param mesh mesh to test
  86944. * @returns true if the mesh will be used
  86945. */
  86946. EffectLayer.prototype.hasMesh = function (mesh) {
  86947. return true;
  86948. };
  86949. /**
  86950. * Returns true if the layer contains information to display, otherwise false.
  86951. * @returns true if the glow layer should be rendered
  86952. */
  86953. EffectLayer.prototype.shouldRender = function () {
  86954. return this.isEnabled && this._shouldRender;
  86955. };
  86956. /**
  86957. * Returns true if the mesh should render, otherwise false.
  86958. * @param mesh The mesh to render
  86959. * @returns true if it should render otherwise false
  86960. */
  86961. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86962. return true;
  86963. };
  86964. /**
  86965. * Returns true if the mesh should render, otherwise false.
  86966. * @param mesh The mesh to render
  86967. * @returns true if it should render otherwise false
  86968. */
  86969. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86970. return true;
  86971. };
  86972. /**
  86973. * Renders the submesh passed in parameter to the generation map.
  86974. */
  86975. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86976. var _this = this;
  86977. if (!this.shouldRender()) {
  86978. return;
  86979. }
  86980. var material = subMesh.getMaterial();
  86981. var mesh = subMesh.getRenderingMesh();
  86982. var scene = this._scene;
  86983. var engine = scene.getEngine();
  86984. if (!material) {
  86985. return;
  86986. }
  86987. // Do not block in blend mode.
  86988. if (material.needAlphaBlendingForMesh(mesh)) {
  86989. return;
  86990. }
  86991. // Culling
  86992. engine.setState(material.backFaceCulling);
  86993. // Managing instances
  86994. var batch = mesh._getInstancesRenderList(subMesh._id);
  86995. if (batch.mustReturn) {
  86996. return;
  86997. }
  86998. // Early Exit per mesh
  86999. if (!this._shouldRenderMesh(mesh)) {
  87000. return;
  87001. }
  87002. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  87003. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  87004. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  87005. engine.enableEffect(this._effectLayerMapGenerationEffect);
  87006. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  87007. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  87008. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  87009. // Alpha test
  87010. if (material && material.needAlphaTesting()) {
  87011. var alphaTexture = material.getAlphaTestTexture();
  87012. if (alphaTexture) {
  87013. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  87014. var textureMatrix = alphaTexture.getTextureMatrix();
  87015. if (textureMatrix) {
  87016. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  87017. }
  87018. }
  87019. }
  87020. // Glow emissive only
  87021. if (this._emissiveTextureAndColor.texture) {
  87022. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  87023. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  87024. }
  87025. // Bones
  87026. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  87027. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  87028. }
  87029. // Morph targets
  87030. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  87031. // Draw
  87032. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  87033. }
  87034. else {
  87035. // Need to reset refresh rate of the shadowMap
  87036. this._mainTexture.resetRefreshCounter();
  87037. }
  87038. };
  87039. /**
  87040. * Rebuild the required buffers.
  87041. * @ignore Internal use only.
  87042. */
  87043. EffectLayer.prototype._rebuild = function () {
  87044. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87045. if (vb) {
  87046. vb._rebuild();
  87047. }
  87048. this._generateIndexBuffer();
  87049. };
  87050. /**
  87051. * Dispose only the render target textures and post process.
  87052. */
  87053. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  87054. this._mainTexture.dispose();
  87055. for (var i = 0; i < this._postProcesses.length; i++) {
  87056. if (this._postProcesses[i]) {
  87057. this._postProcesses[i].dispose();
  87058. }
  87059. }
  87060. this._postProcesses = [];
  87061. for (var i = 0; i < this._textures.length; i++) {
  87062. if (this._textures[i]) {
  87063. this._textures[i].dispose();
  87064. }
  87065. }
  87066. this._textures = [];
  87067. };
  87068. /**
  87069. * Dispose the highlight layer and free resources.
  87070. */
  87071. EffectLayer.prototype.dispose = function () {
  87072. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87073. if (vertexBuffer) {
  87074. vertexBuffer.dispose();
  87075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87076. }
  87077. if (this._indexBuffer) {
  87078. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87079. this._indexBuffer = null;
  87080. }
  87081. // Clean textures and post processes
  87082. this._disposeTextureAndPostProcesses();
  87083. // Remove from scene
  87084. var index = this._scene.effectLayers.indexOf(this, 0);
  87085. if (index > -1) {
  87086. this._scene.effectLayers.splice(index, 1);
  87087. }
  87088. // Callback
  87089. this.onDisposeObservable.notifyObservers(this);
  87090. this.onDisposeObservable.clear();
  87091. this.onBeforeRenderMainTextureObservable.clear();
  87092. this.onBeforeComposeObservable.clear();
  87093. this.onAfterComposeObservable.clear();
  87094. this.onSizeChangedObservable.clear();
  87095. };
  87096. return EffectLayer;
  87097. }());
  87098. BABYLON.EffectLayer = EffectLayer;
  87099. })(BABYLON || (BABYLON = {}));
  87100. //# sourceMappingURL=babylon.effectLayer.js.map
  87101. "use strict";
  87102. var BABYLON;
  87103. (function (BABYLON) {
  87104. /**
  87105. * Special Glow Blur post process only blurring the alpha channel
  87106. * It enforces keeping the most luminous color in the color channel.
  87107. */
  87108. var GlowBlurPostProcess = /** @class */ (function (_super) {
  87109. __extends(GlowBlurPostProcess, _super);
  87110. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  87111. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  87112. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  87113. _this.direction = direction;
  87114. _this.kernel = kernel;
  87115. _this.onApplyObservable.add(function (effect) {
  87116. effect.setFloat2("screenSize", _this.width, _this.height);
  87117. effect.setVector2("direction", _this.direction);
  87118. effect.setFloat("blurWidth", _this.kernel);
  87119. });
  87120. return _this;
  87121. }
  87122. return GlowBlurPostProcess;
  87123. }(BABYLON.PostProcess));
  87124. /**
  87125. * The highlight layer Helps adding a glow effect around a mesh.
  87126. *
  87127. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87128. * glowy meshes to your scene.
  87129. *
  87130. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  87131. */
  87132. var HighlightLayer = /** @class */ (function (_super) {
  87133. __extends(HighlightLayer, _super);
  87134. /**
  87135. * Instantiates a new highlight Layer and references it to the scene..
  87136. * @param name The name of the layer
  87137. * @param scene The scene to use the layer in
  87138. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  87139. */
  87140. function HighlightLayer(name, scene, options) {
  87141. var _this = _super.call(this, name, scene) || this;
  87142. _this.name = name;
  87143. /**
  87144. * Specifies whether or not the inner glow is ACTIVE in the layer.
  87145. */
  87146. _this.innerGlow = true;
  87147. /**
  87148. * Specifies whether or not the outer glow is ACTIVE in the layer.
  87149. */
  87150. _this.outerGlow = true;
  87151. /**
  87152. * An event triggered when the highlight layer is being blurred.
  87153. */
  87154. _this.onBeforeBlurObservable = new BABYLON.Observable();
  87155. /**
  87156. * An event triggered when the highlight layer has been blurred.
  87157. */
  87158. _this.onAfterBlurObservable = new BABYLON.Observable();
  87159. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  87160. _this._meshes = {};
  87161. _this._excludedMeshes = {};
  87162. _this.neutralColor = HighlightLayer.NeutralColor;
  87163. // Warn on stencil
  87164. if (!_this._engine.isStencilEnable) {
  87165. 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 }");
  87166. }
  87167. // Adapt options
  87168. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  87169. // Initialize the layer
  87170. _this._init({
  87171. alphaBlendingMode: _this._options.alphaBlendingMode,
  87172. camera: _this._options.camera,
  87173. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87174. mainTextureRatio: _this._options.mainTextureRatio
  87175. });
  87176. // Do not render as long as no meshes have been added
  87177. _this._shouldRender = false;
  87178. return _this;
  87179. }
  87180. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  87181. /**
  87182. * Gets the horizontal size of the blur.
  87183. */
  87184. get: function () {
  87185. return this._horizontalBlurPostprocess.kernel;
  87186. },
  87187. /**
  87188. * Specifies the horizontal size of the blur.
  87189. */
  87190. set: function (value) {
  87191. this._horizontalBlurPostprocess.kernel = value;
  87192. },
  87193. enumerable: true,
  87194. configurable: true
  87195. });
  87196. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  87197. /**
  87198. * Gets the vertical size of the blur.
  87199. */
  87200. get: function () {
  87201. return this._verticalBlurPostprocess.kernel;
  87202. },
  87203. /**
  87204. * Specifies the vertical size of the blur.
  87205. */
  87206. set: function (value) {
  87207. this._verticalBlurPostprocess.kernel = value;
  87208. },
  87209. enumerable: true,
  87210. configurable: true
  87211. });
  87212. /**
  87213. * Get the effect name of the layer.
  87214. * @return The effect name
  87215. */
  87216. HighlightLayer.prototype.getEffectName = function () {
  87217. return HighlightLayer.EffectName;
  87218. };
  87219. /**
  87220. * Create the merge effect. This is the shader use to blit the information back
  87221. * to the main canvas at the end of the scene rendering.
  87222. */
  87223. HighlightLayer.prototype._createMergeEffect = function () {
  87224. // Effect
  87225. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  87226. };
  87227. /**
  87228. * Creates the render target textures and post processes used in the highlight layer.
  87229. */
  87230. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  87231. var _this = this;
  87232. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  87233. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  87234. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87235. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87236. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  87237. width: blurTextureWidth,
  87238. height: blurTextureHeight
  87239. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87240. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87241. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87242. this._blurTexture.anisotropicFilteringLevel = 16;
  87243. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  87244. this._blurTexture.renderParticles = false;
  87245. this._blurTexture.ignoreCameraViewport = true;
  87246. this._textures = [this._blurTexture];
  87247. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  87248. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87249. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  87250. effect.setTexture("textureSampler", _this._mainTexture);
  87251. });
  87252. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87253. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87254. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87255. });
  87256. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  87257. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  87258. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  87259. });
  87260. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87261. }
  87262. else {
  87263. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  87264. width: blurTextureWidth,
  87265. height: blurTextureHeight
  87266. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87267. this._horizontalBlurPostprocess.width = blurTextureWidth;
  87268. this._horizontalBlurPostprocess.height = blurTextureHeight;
  87269. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  87270. effect.setTexture("textureSampler", _this._mainTexture);
  87271. });
  87272. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  87273. width: blurTextureWidth,
  87274. height: blurTextureHeight
  87275. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87276. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  87277. }
  87278. this._mainTexture.onAfterUnbindObservable.add(function () {
  87279. _this.onBeforeBlurObservable.notifyObservers(_this);
  87280. var internalTexture = _this._blurTexture.getInternalTexture();
  87281. if (internalTexture) {
  87282. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  87283. }
  87284. _this.onAfterBlurObservable.notifyObservers(_this);
  87285. });
  87286. // Prevent autoClear.
  87287. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87288. };
  87289. /**
  87290. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87291. */
  87292. HighlightLayer.prototype.needStencil = function () {
  87293. return true;
  87294. };
  87295. /**
  87296. * Checks for the readiness of the element composing the layer.
  87297. * @param subMesh the mesh to check for
  87298. * @param useInstances specify wether or not to use instances to render the mesh
  87299. * @param emissiveTexture the associated emissive texture used to generate the glow
  87300. * @return true if ready otherwise, false
  87301. */
  87302. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  87303. var material = subMesh.getMaterial();
  87304. var mesh = subMesh.getRenderingMesh();
  87305. if (!material || !mesh || !this._meshes) {
  87306. return false;
  87307. }
  87308. var emissiveTexture = null;
  87309. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87310. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87311. emissiveTexture = material.emissiveTexture;
  87312. }
  87313. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87314. };
  87315. /**
  87316. * Implementation specific of rendering the generating effect on the main canvas.
  87317. * @param effect The effect used to render through
  87318. */
  87319. HighlightLayer.prototype._internalRender = function (effect) {
  87320. // Texture
  87321. effect.setTexture("textureSampler", this._blurTexture);
  87322. // Cache
  87323. var engine = this._engine;
  87324. var previousStencilBuffer = engine.getStencilBuffer();
  87325. var previousStencilFunction = engine.getStencilFunction();
  87326. var previousStencilMask = engine.getStencilMask();
  87327. var previousStencilOperationPass = engine.getStencilOperationPass();
  87328. var previousStencilOperationFail = engine.getStencilOperationFail();
  87329. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  87330. var previousStencilReference = engine.getStencilFunctionReference();
  87331. // Stencil operations
  87332. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  87333. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  87334. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  87335. // Draw order
  87336. engine.setStencilMask(0x00);
  87337. engine.setStencilBuffer(true);
  87338. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  87339. // 2 passes inner outer
  87340. if (this.outerGlow) {
  87341. effect.setFloat("offset", 0);
  87342. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  87343. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87344. }
  87345. if (this.innerGlow) {
  87346. effect.setFloat("offset", 1);
  87347. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  87348. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87349. }
  87350. // Restore Cache
  87351. engine.setStencilFunction(previousStencilFunction);
  87352. engine.setStencilMask(previousStencilMask);
  87353. engine.setStencilBuffer(previousStencilBuffer);
  87354. engine.setStencilOperationPass(previousStencilOperationPass);
  87355. engine.setStencilOperationFail(previousStencilOperationFail);
  87356. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  87357. engine.setStencilFunctionReference(previousStencilReference);
  87358. };
  87359. /**
  87360. * Returns true if the layer contains information to display, otherwise false.
  87361. */
  87362. HighlightLayer.prototype.shouldRender = function () {
  87363. if (_super.prototype.shouldRender.call(this)) {
  87364. return this._meshes ? true : false;
  87365. }
  87366. return false;
  87367. };
  87368. /**
  87369. * Returns true if the mesh should render, otherwise false.
  87370. * @param mesh The mesh to render
  87371. * @returns true if it should render otherwise false
  87372. */
  87373. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  87374. // Excluded Mesh
  87375. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  87376. return false;
  87377. }
  87378. ;
  87379. return true;
  87380. };
  87381. /**
  87382. * Sets the required values for both the emissive texture and and the main color.
  87383. */
  87384. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87385. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  87386. if (highlightLayerMesh) {
  87387. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  87388. }
  87389. else {
  87390. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87391. }
  87392. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  87393. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87394. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  87395. }
  87396. else {
  87397. this._emissiveTextureAndColor.texture = null;
  87398. }
  87399. };
  87400. /**
  87401. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  87402. * @param mesh The mesh to exclude from the highlight layer
  87403. */
  87404. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  87405. if (!this._excludedMeshes) {
  87406. return;
  87407. }
  87408. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87409. if (!meshExcluded) {
  87410. this._excludedMeshes[mesh.uniqueId] = {
  87411. mesh: mesh,
  87412. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  87413. mesh.getEngine().setStencilBuffer(false);
  87414. }),
  87415. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  87416. mesh.getEngine().setStencilBuffer(true);
  87417. }),
  87418. };
  87419. }
  87420. };
  87421. /**
  87422. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  87423. * @param mesh The mesh to highlight
  87424. */
  87425. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  87426. if (!this._excludedMeshes) {
  87427. return;
  87428. }
  87429. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  87430. if (meshExcluded) {
  87431. if (meshExcluded.beforeRender) {
  87432. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  87433. }
  87434. if (meshExcluded.afterRender) {
  87435. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  87436. }
  87437. }
  87438. this._excludedMeshes[mesh.uniqueId] = null;
  87439. };
  87440. /**
  87441. * Determine if a given mesh will be highlighted by the current HighlightLayer
  87442. * @param mesh mesh to test
  87443. * @returns true if the mesh will be highlighted by the current HighlightLayer
  87444. */
  87445. HighlightLayer.prototype.hasMesh = function (mesh) {
  87446. if (!this._meshes) {
  87447. return false;
  87448. }
  87449. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  87450. };
  87451. /**
  87452. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  87453. * @param mesh The mesh to highlight
  87454. * @param color The color of the highlight
  87455. * @param glowEmissiveOnly Extract the glow from the emissive texture
  87456. */
  87457. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  87458. var _this = this;
  87459. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  87460. if (!this._meshes) {
  87461. return;
  87462. }
  87463. var meshHighlight = this._meshes[mesh.uniqueId];
  87464. if (meshHighlight) {
  87465. meshHighlight.color = color;
  87466. }
  87467. else {
  87468. this._meshes[mesh.uniqueId] = {
  87469. mesh: mesh,
  87470. color: color,
  87471. // Lambda required for capture due to Observable this context
  87472. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  87473. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  87474. _this._defaultStencilReference(mesh);
  87475. }
  87476. else {
  87477. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  87478. }
  87479. }),
  87480. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  87481. glowEmissiveOnly: glowEmissiveOnly
  87482. };
  87483. }
  87484. this._shouldRender = true;
  87485. };
  87486. /**
  87487. * Remove a mesh from the highlight layer in order to make it stop glowing.
  87488. * @param mesh The mesh to highlight
  87489. */
  87490. HighlightLayer.prototype.removeMesh = function (mesh) {
  87491. if (!this._meshes) {
  87492. return;
  87493. }
  87494. var meshHighlight = this._meshes[mesh.uniqueId];
  87495. if (meshHighlight) {
  87496. if (meshHighlight.observerHighlight) {
  87497. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87498. }
  87499. if (meshHighlight.observerDefault) {
  87500. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87501. }
  87502. delete this._meshes[mesh.uniqueId];
  87503. }
  87504. this._shouldRender = false;
  87505. for (var meshHighlightToCheck in this._meshes) {
  87506. if (this._meshes[meshHighlightToCheck]) {
  87507. this._shouldRender = true;
  87508. break;
  87509. }
  87510. }
  87511. };
  87512. /**
  87513. * Force the stencil to the normal expected value for none glowing parts
  87514. */
  87515. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  87516. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  87517. };
  87518. /**
  87519. * Free any resources and references associated to a mesh.
  87520. * Internal use
  87521. * @param mesh The mesh to free.
  87522. */
  87523. HighlightLayer.prototype._disposeMesh = function (mesh) {
  87524. this.removeMesh(mesh);
  87525. this.removeExcludedMesh(mesh);
  87526. };
  87527. /**
  87528. * Dispose the highlight layer and free resources.
  87529. */
  87530. HighlightLayer.prototype.dispose = function () {
  87531. if (this._meshes) {
  87532. // Clean mesh references
  87533. for (var id in this._meshes) {
  87534. var meshHighlight = this._meshes[id];
  87535. if (meshHighlight && meshHighlight.mesh) {
  87536. if (meshHighlight.observerHighlight) {
  87537. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  87538. }
  87539. if (meshHighlight.observerDefault) {
  87540. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  87541. }
  87542. }
  87543. }
  87544. this._meshes = null;
  87545. }
  87546. if (this._excludedMeshes) {
  87547. for (var id in this._excludedMeshes) {
  87548. var meshHighlight = this._excludedMeshes[id];
  87549. if (meshHighlight) {
  87550. if (meshHighlight.beforeRender) {
  87551. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87552. }
  87553. if (meshHighlight.afterRender) {
  87554. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87555. }
  87556. }
  87557. }
  87558. this._excludedMeshes = null;
  87559. }
  87560. _super.prototype.dispose.call(this);
  87561. };
  87562. /**
  87563. * Effect Name of the highlight layer.
  87564. */
  87565. HighlightLayer.EffectName = "HighlightLayer";
  87566. /**
  87567. * The neutral color used during the preparation of the glow effect.
  87568. * This is black by default as the blend operation is a blend operation.
  87569. */
  87570. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87571. /**
  87572. * Stencil value used for glowing meshes.
  87573. */
  87574. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87575. /**
  87576. * Stencil value used for the other meshes in the scene.
  87577. */
  87578. HighlightLayer.NormalMeshStencilReference = 0x01;
  87579. return HighlightLayer;
  87580. }(BABYLON.EffectLayer));
  87581. BABYLON.HighlightLayer = HighlightLayer;
  87582. })(BABYLON || (BABYLON = {}));
  87583. //# sourceMappingURL=babylon.highlightLayer.js.map
  87584. "use strict";
  87585. var BABYLON;
  87586. (function (BABYLON) {
  87587. /**
  87588. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87589. *
  87590. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87591. * glowy meshes to your scene.
  87592. *
  87593. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87594. */
  87595. var GlowLayer = /** @class */ (function (_super) {
  87596. __extends(GlowLayer, _super);
  87597. /**
  87598. * Instantiates a new glow Layer and references it to the scene.
  87599. * @param name The name of the layer
  87600. * @param scene The scene to use the layer in
  87601. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87602. */
  87603. function GlowLayer(name, scene, options) {
  87604. var _this = _super.call(this, name, scene) || this;
  87605. _this.name = name;
  87606. _this._intensity = 1.0;
  87607. _this._includedOnlyMeshes = [];
  87608. _this._excludedMeshes = [];
  87609. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87610. // Adapt options
  87611. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87612. // Initialize the layer
  87613. _this._init({
  87614. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87615. camera: _this._options.camera,
  87616. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87617. mainTextureRatio: _this._options.mainTextureRatio
  87618. });
  87619. return _this;
  87620. }
  87621. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87622. /**
  87623. * Gets the kernel size of the blur.
  87624. */
  87625. get: function () {
  87626. return this._horizontalBlurPostprocess1.kernel;
  87627. },
  87628. /**
  87629. * Sets the kernel size of the blur.
  87630. */
  87631. set: function (value) {
  87632. this._horizontalBlurPostprocess1.kernel = value;
  87633. this._verticalBlurPostprocess1.kernel = value;
  87634. this._horizontalBlurPostprocess2.kernel = value;
  87635. this._verticalBlurPostprocess2.kernel = value;
  87636. },
  87637. enumerable: true,
  87638. configurable: true
  87639. });
  87640. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87641. /**
  87642. * Gets the glow intensity.
  87643. */
  87644. get: function () {
  87645. return this._intensity;
  87646. },
  87647. /**
  87648. * Sets the glow intensity.
  87649. */
  87650. set: function (value) {
  87651. this._intensity = value;
  87652. },
  87653. enumerable: true,
  87654. configurable: true
  87655. });
  87656. /**
  87657. * Get the effect name of the layer.
  87658. * @return The effect name
  87659. */
  87660. GlowLayer.prototype.getEffectName = function () {
  87661. return GlowLayer.EffectName;
  87662. };
  87663. /**
  87664. * Create the merge effect. This is the shader use to blit the information back
  87665. * to the main canvas at the end of the scene rendering.
  87666. */
  87667. GlowLayer.prototype._createMergeEffect = function () {
  87668. // Effect
  87669. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87670. };
  87671. /**
  87672. * Creates the render target textures and post processes used in the glow layer.
  87673. */
  87674. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87675. var _this = this;
  87676. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87677. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87678. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87679. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87680. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87681. width: blurTextureWidth,
  87682. height: blurTextureHeight
  87683. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87684. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87685. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87686. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87687. this._blurTexture1.renderParticles = false;
  87688. this._blurTexture1.ignoreCameraViewport = true;
  87689. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87690. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87691. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87692. width: blurTextureWidth2,
  87693. height: blurTextureHeight2
  87694. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87695. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87696. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87697. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87698. this._blurTexture2.renderParticles = false;
  87699. this._blurTexture2.ignoreCameraViewport = true;
  87700. this._textures = [this._blurTexture1, this._blurTexture2];
  87701. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87702. width: blurTextureWidth,
  87703. height: blurTextureHeight
  87704. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87705. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87706. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87707. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87708. effect.setTexture("textureSampler", _this._mainTexture);
  87709. });
  87710. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87711. width: blurTextureWidth,
  87712. height: blurTextureHeight
  87713. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87714. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87715. width: blurTextureWidth2,
  87716. height: blurTextureHeight2
  87717. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87718. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87719. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87720. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87721. effect.setTexture("textureSampler", _this._blurTexture1);
  87722. });
  87723. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87724. width: blurTextureWidth2,
  87725. height: blurTextureHeight2
  87726. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87727. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87728. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87729. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87730. this._mainTexture.samples = this._options.mainTextureSamples;
  87731. this._mainTexture.onAfterUnbindObservable.add(function () {
  87732. var internalTexture = _this._blurTexture1.getInternalTexture();
  87733. if (internalTexture) {
  87734. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87735. internalTexture = _this._blurTexture2.getInternalTexture();
  87736. if (internalTexture) {
  87737. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87738. }
  87739. }
  87740. });
  87741. // Prevent autoClear.
  87742. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87743. };
  87744. /**
  87745. * Checks for the readiness of the element composing the layer.
  87746. * @param subMesh the mesh to check for
  87747. * @param useInstances specify wether or not to use instances to render the mesh
  87748. * @param emissiveTexture the associated emissive texture used to generate the glow
  87749. * @return true if ready otherwise, false
  87750. */
  87751. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87752. var material = subMesh.getMaterial();
  87753. var mesh = subMesh.getRenderingMesh();
  87754. if (!material || !mesh) {
  87755. return false;
  87756. }
  87757. var emissiveTexture = material.emissiveTexture;
  87758. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87759. };
  87760. /**
  87761. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87762. */
  87763. GlowLayer.prototype.needStencil = function () {
  87764. return false;
  87765. };
  87766. /**
  87767. * Implementation specific of rendering the generating effect on the main canvas.
  87768. * @param effect The effect used to render through
  87769. */
  87770. GlowLayer.prototype._internalRender = function (effect) {
  87771. // Texture
  87772. effect.setTexture("textureSampler", this._blurTexture1);
  87773. effect.setTexture("textureSampler2", this._blurTexture2);
  87774. effect.setFloat("offset", this._intensity);
  87775. // Cache
  87776. var engine = this._engine;
  87777. var previousStencilBuffer = engine.getStencilBuffer();
  87778. // Draw order
  87779. engine.setStencilBuffer(false);
  87780. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87781. // Draw order
  87782. engine.setStencilBuffer(previousStencilBuffer);
  87783. };
  87784. /**
  87785. * Sets the required values for both the emissive texture and and the main color.
  87786. */
  87787. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87788. var textureLevel = 1.0;
  87789. if (this.customEmissiveTextureSelector) {
  87790. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87791. }
  87792. else {
  87793. if (material) {
  87794. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87795. if (this._emissiveTextureAndColor.texture) {
  87796. textureLevel = this._emissiveTextureAndColor.texture.level;
  87797. }
  87798. }
  87799. else {
  87800. this._emissiveTextureAndColor.texture = null;
  87801. }
  87802. }
  87803. if (this.customEmissiveColorSelector) {
  87804. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87805. }
  87806. else {
  87807. if (material.emissiveColor) {
  87808. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87809. }
  87810. else {
  87811. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87812. }
  87813. }
  87814. };
  87815. /**
  87816. * Returns true if the mesh should render, otherwise false.
  87817. * @param mesh The mesh to render
  87818. * @returns true if it should render otherwise false
  87819. */
  87820. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87821. return this.hasMesh(mesh);
  87822. };
  87823. /**
  87824. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87825. * @param mesh The mesh to exclude from the glow layer
  87826. */
  87827. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87828. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87829. this._excludedMeshes.push(mesh.uniqueId);
  87830. }
  87831. };
  87832. /**
  87833. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87834. * @param mesh The mesh to remove
  87835. */
  87836. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87837. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87838. if (index !== -1) {
  87839. this._excludedMeshes.splice(index, 1);
  87840. }
  87841. };
  87842. /**
  87843. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87844. * @param mesh The mesh to include in the glow layer
  87845. */
  87846. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87847. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87848. this._includedOnlyMeshes.push(mesh.uniqueId);
  87849. }
  87850. };
  87851. /**
  87852. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87853. * @param mesh The mesh to remove
  87854. */
  87855. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87856. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87857. if (index !== -1) {
  87858. this._includedOnlyMeshes.splice(index, 1);
  87859. }
  87860. };
  87861. /**
  87862. * Determine if a given mesh will be used in the glow layer
  87863. * @param mesh The mesh to test
  87864. * @returns true if the mesh will be highlighted by the current glow layer
  87865. */
  87866. GlowLayer.prototype.hasMesh = function (mesh) {
  87867. // Included Mesh
  87868. if (this._includedOnlyMeshes.length) {
  87869. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87870. }
  87871. ;
  87872. // Excluded Mesh
  87873. if (this._excludedMeshes.length) {
  87874. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87875. }
  87876. ;
  87877. return true;
  87878. };
  87879. /**
  87880. * Free any resources and references associated to a mesh.
  87881. * Internal use
  87882. * @param mesh The mesh to free.
  87883. */
  87884. GlowLayer.prototype._disposeMesh = function (mesh) {
  87885. this.removeIncludedOnlyMesh(mesh);
  87886. this.removeExcludedMesh(mesh);
  87887. };
  87888. /**
  87889. * Effect Name of the layer.
  87890. */
  87891. GlowLayer.EffectName = "GlowLayer";
  87892. /**
  87893. * The default blur kernel size used for the glow.
  87894. */
  87895. GlowLayer.DefaultBlurKernelSize = 32;
  87896. /**
  87897. * The default texture size ratio used for the glow.
  87898. */
  87899. GlowLayer.DefaultTextureRatio = 0.5;
  87900. return GlowLayer;
  87901. }(BABYLON.EffectLayer));
  87902. BABYLON.GlowLayer = GlowLayer;
  87903. })(BABYLON || (BABYLON = {}));
  87904. //# sourceMappingURL=babylon.glowLayer.js.map
  87905. "use strict";
  87906. var BABYLON;
  87907. (function (BABYLON) {
  87908. /**
  87909. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87910. */
  87911. var AssetTaskState;
  87912. (function (AssetTaskState) {
  87913. /**
  87914. * Initialization
  87915. */
  87916. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87917. /**
  87918. * Running
  87919. */
  87920. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87921. /**
  87922. * Done
  87923. */
  87924. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87925. /**
  87926. * Error
  87927. */
  87928. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87929. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87930. /**
  87931. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87932. */
  87933. var AbstractAssetTask = /** @class */ (function () {
  87934. /**
  87935. * Creates a new {BABYLON.AssetsManager}
  87936. * @param name defines the name of the task
  87937. */
  87938. function AbstractAssetTask(
  87939. /**
  87940. * Task name
  87941. */ name) {
  87942. this.name = name;
  87943. this._isCompleted = false;
  87944. this._taskState = AssetTaskState.INIT;
  87945. }
  87946. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87947. /**
  87948. * Get if the task is completed
  87949. */
  87950. get: function () {
  87951. return this._isCompleted;
  87952. },
  87953. enumerable: true,
  87954. configurable: true
  87955. });
  87956. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87957. /**
  87958. * Gets the current state of the task
  87959. */
  87960. get: function () {
  87961. return this._taskState;
  87962. },
  87963. enumerable: true,
  87964. configurable: true
  87965. });
  87966. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87967. /**
  87968. * Gets the current error object (if task is in error)
  87969. */
  87970. get: function () {
  87971. return this._errorObject;
  87972. },
  87973. enumerable: true,
  87974. configurable: true
  87975. });
  87976. /**
  87977. * Internal only
  87978. * @ignore
  87979. */
  87980. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87981. if (this._errorObject) {
  87982. return;
  87983. }
  87984. this._errorObject = {
  87985. message: message,
  87986. exception: exception
  87987. };
  87988. };
  87989. /**
  87990. * Execute the current task
  87991. * @param scene defines the scene where you want your assets to be loaded
  87992. * @param onSuccess is a callback called when the task is successfully executed
  87993. * @param onError is a callback called if an error occurs
  87994. */
  87995. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87996. var _this = this;
  87997. this._taskState = AssetTaskState.RUNNING;
  87998. this.runTask(scene, function () {
  87999. _this.onDoneCallback(onSuccess, onError);
  88000. }, function (msg, exception) {
  88001. _this.onErrorCallback(onError, msg, exception);
  88002. });
  88003. };
  88004. /**
  88005. * Execute the current task
  88006. * @param scene defines the scene where you want your assets to be loaded
  88007. * @param onSuccess is a callback called when the task is successfully executed
  88008. * @param onError is a callback called if an error occurs
  88009. */
  88010. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88011. throw new Error("runTask is not implemented");
  88012. };
  88013. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  88014. this._taskState = AssetTaskState.ERROR;
  88015. this._errorObject = {
  88016. message: message,
  88017. exception: exception
  88018. };
  88019. if (this.onError) {
  88020. this.onError(this, message, exception);
  88021. }
  88022. onError();
  88023. };
  88024. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  88025. try {
  88026. this._taskState = AssetTaskState.DONE;
  88027. this._isCompleted = true;
  88028. if (this.onSuccess) {
  88029. this.onSuccess(this);
  88030. }
  88031. onSuccess();
  88032. }
  88033. catch (e) {
  88034. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  88035. }
  88036. };
  88037. return AbstractAssetTask;
  88038. }());
  88039. BABYLON.AbstractAssetTask = AbstractAssetTask;
  88040. /**
  88041. * Class used to share progress information about assets loading
  88042. */
  88043. var AssetsProgressEvent = /** @class */ (function () {
  88044. /**
  88045. * Creates a {BABYLON.AssetsProgressEvent}
  88046. * @param remainingCount defines the number of remaining tasks to process
  88047. * @param totalCount defines the total number of tasks
  88048. * @param task defines the task that was just processed
  88049. */
  88050. function AssetsProgressEvent(remainingCount, totalCount, task) {
  88051. this.remainingCount = remainingCount;
  88052. this.totalCount = totalCount;
  88053. this.task = task;
  88054. }
  88055. return AssetsProgressEvent;
  88056. }());
  88057. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  88058. /**
  88059. * Define a task used by {BABYLON.AssetsManager} to load meshes
  88060. */
  88061. var MeshAssetTask = /** @class */ (function (_super) {
  88062. __extends(MeshAssetTask, _super);
  88063. /**
  88064. * Creates a new {BABYLON.MeshAssetTask}
  88065. * @param name defines the name of the task
  88066. * @param meshesNames defines the list of mesh's names you want to load
  88067. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  88068. * @param sceneFilename defines the filename of the scene to load from
  88069. */
  88070. function MeshAssetTask(
  88071. /**
  88072. * Defines the name of the task
  88073. */
  88074. name,
  88075. /**
  88076. * Defines the list of mesh's names you want to load
  88077. */
  88078. meshesNames,
  88079. /**
  88080. * Defines the root url to use as a base to load your meshes and associated resources
  88081. */
  88082. rootUrl,
  88083. /**
  88084. * Defines the filename of the scene to load from
  88085. */
  88086. sceneFilename) {
  88087. var _this = _super.call(this, name) || this;
  88088. _this.name = name;
  88089. _this.meshesNames = meshesNames;
  88090. _this.rootUrl = rootUrl;
  88091. _this.sceneFilename = sceneFilename;
  88092. return _this;
  88093. }
  88094. /**
  88095. * Execute the current task
  88096. * @param scene defines the scene where you want your assets to be loaded
  88097. * @param onSuccess is a callback called when the task is successfully executed
  88098. * @param onError is a callback called if an error occurs
  88099. */
  88100. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88101. var _this = this;
  88102. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  88103. _this.loadedMeshes = meshes;
  88104. _this.loadedParticleSystems = particleSystems;
  88105. _this.loadedSkeletons = skeletons;
  88106. onSuccess();
  88107. }, null, function (scene, message, exception) {
  88108. onError(message, exception);
  88109. });
  88110. };
  88111. return MeshAssetTask;
  88112. }(AbstractAssetTask));
  88113. BABYLON.MeshAssetTask = MeshAssetTask;
  88114. /**
  88115. * Define a task used by {BABYLON.AssetsManager} to load text content
  88116. */
  88117. var TextFileAssetTask = /** @class */ (function (_super) {
  88118. __extends(TextFileAssetTask, _super);
  88119. /**
  88120. * Creates a new TextFileAssetTask object
  88121. * @param name defines the name of the task
  88122. * @param url defines the location of the file to load
  88123. */
  88124. function TextFileAssetTask(
  88125. /**
  88126. * Defines the name of the task
  88127. */
  88128. name,
  88129. /**
  88130. * Defines the location of the file to load
  88131. */
  88132. url) {
  88133. var _this = _super.call(this, name) || this;
  88134. _this.name = name;
  88135. _this.url = url;
  88136. return _this;
  88137. }
  88138. /**
  88139. * Execute the current task
  88140. * @param scene defines the scene where you want your assets to be loaded
  88141. * @param onSuccess is a callback called when the task is successfully executed
  88142. * @param onError is a callback called if an error occurs
  88143. */
  88144. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88145. var _this = this;
  88146. scene._loadFile(this.url, function (data) {
  88147. _this.text = data;
  88148. onSuccess();
  88149. }, undefined, false, false, function (request, exception) {
  88150. if (request) {
  88151. onError(request.status + " " + request.statusText, exception);
  88152. }
  88153. });
  88154. };
  88155. return TextFileAssetTask;
  88156. }(AbstractAssetTask));
  88157. BABYLON.TextFileAssetTask = TextFileAssetTask;
  88158. /**
  88159. * Define a task used by {BABYLON.AssetsManager} to load binary data
  88160. */
  88161. var BinaryFileAssetTask = /** @class */ (function (_super) {
  88162. __extends(BinaryFileAssetTask, _super);
  88163. /**
  88164. * Creates a new BinaryFileAssetTask object
  88165. * @param name defines the name of the new task
  88166. * @param url defines the location of the file to load
  88167. */
  88168. function BinaryFileAssetTask(
  88169. /**
  88170. * Defines the name of the task
  88171. */
  88172. name,
  88173. /**
  88174. * Defines the location of the file to load
  88175. */
  88176. url) {
  88177. var _this = _super.call(this, name) || this;
  88178. _this.name = name;
  88179. _this.url = url;
  88180. return _this;
  88181. }
  88182. /**
  88183. * Execute the current task
  88184. * @param scene defines the scene where you want your assets to be loaded
  88185. * @param onSuccess is a callback called when the task is successfully executed
  88186. * @param onError is a callback called if an error occurs
  88187. */
  88188. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88189. var _this = this;
  88190. scene._loadFile(this.url, function (data) {
  88191. _this.data = data;
  88192. onSuccess();
  88193. }, undefined, true, true, function (request, exception) {
  88194. if (request) {
  88195. onError(request.status + " " + request.statusText, exception);
  88196. }
  88197. });
  88198. };
  88199. return BinaryFileAssetTask;
  88200. }(AbstractAssetTask));
  88201. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  88202. /**
  88203. * Define a task used by {BABYLON.AssetsManager} to load images
  88204. */
  88205. var ImageAssetTask = /** @class */ (function (_super) {
  88206. __extends(ImageAssetTask, _super);
  88207. /**
  88208. * Creates a new ImageAssetTask
  88209. * @param name defines the name of the task
  88210. * @param url defines the location of the image to load
  88211. */
  88212. function ImageAssetTask(
  88213. /**
  88214. * Defines the name of the task
  88215. */
  88216. name,
  88217. /**
  88218. * Defines the location of the image to load
  88219. */
  88220. url) {
  88221. var _this = _super.call(this, name) || this;
  88222. _this.name = name;
  88223. _this.url = url;
  88224. return _this;
  88225. }
  88226. /**
  88227. * Execute the current task
  88228. * @param scene defines the scene where you want your assets to be loaded
  88229. * @param onSuccess is a callback called when the task is successfully executed
  88230. * @param onError is a callback called if an error occurs
  88231. */
  88232. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88233. var _this = this;
  88234. var img = new Image();
  88235. BABYLON.Tools.SetCorsBehavior(this.url, img);
  88236. img.onload = function () {
  88237. _this.image = img;
  88238. onSuccess();
  88239. };
  88240. img.onerror = function (err) {
  88241. onError("Error loading image", err);
  88242. };
  88243. img.src = this.url;
  88244. };
  88245. return ImageAssetTask;
  88246. }(AbstractAssetTask));
  88247. BABYLON.ImageAssetTask = ImageAssetTask;
  88248. /**
  88249. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  88250. */
  88251. var TextureAssetTask = /** @class */ (function (_super) {
  88252. __extends(TextureAssetTask, _super);
  88253. /**
  88254. * Creates a new TextureAssetTask object
  88255. * @param name defines the name of the task
  88256. * @param url defines the location of the file to load
  88257. * @param noMipmap defines if mipmap should not be generated (default is false)
  88258. * @param invertY defines if texture must be inverted on Y axis (default is false)
  88259. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88260. */
  88261. function TextureAssetTask(
  88262. /**
  88263. * Defines the name of the task
  88264. */
  88265. name,
  88266. /**
  88267. * Defines the location of the file to load
  88268. */
  88269. url,
  88270. /**
  88271. * Defines if mipmap should not be generated (default is false)
  88272. */
  88273. noMipmap,
  88274. /**
  88275. * Defines if texture must be inverted on Y axis (default is false)
  88276. */
  88277. invertY,
  88278. /**
  88279. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  88280. */
  88281. samplingMode) {
  88282. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88283. var _this = _super.call(this, name) || this;
  88284. _this.name = name;
  88285. _this.url = url;
  88286. _this.noMipmap = noMipmap;
  88287. _this.invertY = invertY;
  88288. _this.samplingMode = samplingMode;
  88289. return _this;
  88290. }
  88291. /**
  88292. * Execute the current task
  88293. * @param scene defines the scene where you want your assets to be loaded
  88294. * @param onSuccess is a callback called when the task is successfully executed
  88295. * @param onError is a callback called if an error occurs
  88296. */
  88297. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88298. var onload = function () {
  88299. onSuccess();
  88300. };
  88301. var onerror = function (message, exception) {
  88302. onError(message, exception);
  88303. };
  88304. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  88305. };
  88306. return TextureAssetTask;
  88307. }(AbstractAssetTask));
  88308. BABYLON.TextureAssetTask = TextureAssetTask;
  88309. /**
  88310. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  88311. */
  88312. var CubeTextureAssetTask = /** @class */ (function (_super) {
  88313. __extends(CubeTextureAssetTask, _super);
  88314. /**
  88315. * Creates a new CubeTextureAssetTask
  88316. * @param name defines the name of the task
  88317. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88318. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88319. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88320. * @param files defines the explicit list of files (undefined by default)
  88321. */
  88322. function CubeTextureAssetTask(
  88323. /**
  88324. * Defines the name of the task
  88325. */
  88326. name,
  88327. /**
  88328. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  88329. */
  88330. url,
  88331. /**
  88332. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  88333. */
  88334. extensions,
  88335. /**
  88336. * Defines if mipmaps should not be generated (default is false)
  88337. */
  88338. noMipmap,
  88339. /**
  88340. * Defines the explicit list of files (undefined by default)
  88341. */
  88342. files) {
  88343. var _this = _super.call(this, name) || this;
  88344. _this.name = name;
  88345. _this.url = url;
  88346. _this.extensions = extensions;
  88347. _this.noMipmap = noMipmap;
  88348. _this.files = files;
  88349. return _this;
  88350. }
  88351. /**
  88352. * Execute the current task
  88353. * @param scene defines the scene where you want your assets to be loaded
  88354. * @param onSuccess is a callback called when the task is successfully executed
  88355. * @param onError is a callback called if an error occurs
  88356. */
  88357. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  88358. var onload = function () {
  88359. onSuccess();
  88360. };
  88361. var onerror = function (message, exception) {
  88362. onError(message, exception);
  88363. };
  88364. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  88365. };
  88366. return CubeTextureAssetTask;
  88367. }(AbstractAssetTask));
  88368. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  88369. /**
  88370. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  88371. */
  88372. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  88373. __extends(HDRCubeTextureAssetTask, _super);
  88374. /**
  88375. * Creates a new HDRCubeTextureAssetTask object
  88376. * @param name defines the name of the task
  88377. * @param url defines the location of the file to load
  88378. * @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.
  88379. * @param noMipmap defines if mipmaps should not be generated (default is false)
  88380. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88381. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  88382. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88383. */
  88384. function HDRCubeTextureAssetTask(
  88385. /**
  88386. * Defines the name of the task
  88387. */
  88388. name,
  88389. /**
  88390. * Defines the location of the file to load
  88391. */
  88392. url,
  88393. /**
  88394. * 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.
  88395. */
  88396. size,
  88397. /**
  88398. * Defines if mipmaps should not be generated (default is false)
  88399. */
  88400. noMipmap,
  88401. /**
  88402. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  88403. */
  88404. generateHarmonics,
  88405. /**
  88406. * 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)
  88407. */
  88408. useInGammaSpace,
  88409. /**
  88410. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  88411. */
  88412. usePMREMGenerator) {
  88413. if (noMipmap === void 0) { noMipmap = false; }
  88414. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88415. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88416. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88417. var _this = _super.call(this, name) || this;
  88418. _this.name = name;
  88419. _this.url = url;
  88420. _this.size = size;
  88421. _this.noMipmap = noMipmap;
  88422. _this.generateHarmonics = generateHarmonics;
  88423. _this.useInGammaSpace = useInGammaSpace;
  88424. _this.usePMREMGenerator = usePMREMGenerator;
  88425. return _this;
  88426. }
  88427. /**
  88428. * Execute the current task
  88429. * @param scene defines the scene where you want your assets to be loaded
  88430. * @param onSuccess is a callback called when the task is successfully executed
  88431. * @param onError is a callback called if an error occurs
  88432. */
  88433. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  88434. var onload = function () {
  88435. onSuccess();
  88436. };
  88437. var onerror = function (message, exception) {
  88438. onError(message, exception);
  88439. };
  88440. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  88441. };
  88442. return HDRCubeTextureAssetTask;
  88443. }(AbstractAssetTask));
  88444. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  88445. /**
  88446. * This class can be used to easily import assets into a scene
  88447. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  88448. */
  88449. var AssetsManager = /** @class */ (function () {
  88450. /**
  88451. * Creates a new AssetsManager
  88452. * @param scene defines the scene to work on
  88453. */
  88454. function AssetsManager(scene) {
  88455. this._isLoading = false;
  88456. this._tasks = new Array();
  88457. this._waitingTasksCount = 0;
  88458. this._totalTasksCount = 0;
  88459. /**
  88460. * Observable called when all tasks are processed
  88461. */
  88462. this.onTaskSuccessObservable = new BABYLON.Observable();
  88463. /**
  88464. * Observable called when a task had an error
  88465. */
  88466. this.onTaskErrorObservable = new BABYLON.Observable();
  88467. /**
  88468. * Observable called when a task is successful
  88469. */
  88470. this.onTasksDoneObservable = new BABYLON.Observable();
  88471. /**
  88472. * Observable called when a task is done (whatever the result is)
  88473. */
  88474. this.onProgressObservable = new BABYLON.Observable();
  88475. /**
  88476. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  88477. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  88478. */
  88479. this.useDefaultLoadingScreen = true;
  88480. this._scene = scene;
  88481. }
  88482. /**
  88483. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  88484. * @param taskName defines the name of the new task
  88485. * @param meshesNames defines the name of meshes to load
  88486. * @param rootUrl defines the root url to use to locate files
  88487. * @param sceneFilename defines the filename of the scene file
  88488. * @returns a new {BABYLON.MeshAssetTask} object
  88489. */
  88490. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  88491. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  88492. this._tasks.push(task);
  88493. return task;
  88494. };
  88495. /**
  88496. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  88497. * @param taskName defines the name of the new task
  88498. * @param url defines the url of the file to load
  88499. * @returns a new {BABYLON.TextFileAssetTask} object
  88500. */
  88501. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  88502. var task = new TextFileAssetTask(taskName, url);
  88503. this._tasks.push(task);
  88504. return task;
  88505. };
  88506. /**
  88507. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  88508. * @param taskName defines the name of the new task
  88509. * @param url defines the url of the file to load
  88510. * @returns a new {BABYLON.BinaryFileAssetTask} object
  88511. */
  88512. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  88513. var task = new BinaryFileAssetTask(taskName, url);
  88514. this._tasks.push(task);
  88515. return task;
  88516. };
  88517. /**
  88518. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  88519. * @param taskName defines the name of the new task
  88520. * @param url defines the url of the file to load
  88521. * @returns a new {BABYLON.ImageAssetTask} object
  88522. */
  88523. AssetsManager.prototype.addImageTask = function (taskName, url) {
  88524. var task = new ImageAssetTask(taskName, url);
  88525. this._tasks.push(task);
  88526. return task;
  88527. };
  88528. /**
  88529. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  88530. * @param taskName defines the name of the new task
  88531. * @param url defines the url of the file to load
  88532. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88533. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  88534. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  88535. * @returns a new {BABYLON.TextureAssetTask} object
  88536. */
  88537. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  88538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  88539. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  88540. this._tasks.push(task);
  88541. return task;
  88542. };
  88543. /**
  88544. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  88545. * @param taskName defines the name of the new task
  88546. * @param url defines the url of the file to load
  88547. * @param extensions defines the extension to use to load the cube map (can be null)
  88548. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88549. * @param files defines the list of files to load (can be null)
  88550. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88551. */
  88552. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88553. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88554. this._tasks.push(task);
  88555. return task;
  88556. };
  88557. /**
  88558. *
  88559. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88560. * @param taskName defines the name of the new task
  88561. * @param url defines the url of the file to load
  88562. * @param size defines the size you want for the cubemap (can be null)
  88563. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88564. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88565. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88566. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88567. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88568. */
  88569. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88570. if (noMipmap === void 0) { noMipmap = false; }
  88571. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88572. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88573. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88574. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88575. this._tasks.push(task);
  88576. return task;
  88577. };
  88578. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88579. var _this = this;
  88580. this._waitingTasksCount--;
  88581. try {
  88582. if (task.taskState === AssetTaskState.DONE) {
  88583. // Let's remove successfull tasks
  88584. BABYLON.Tools.SetImmediate(function () {
  88585. var index = _this._tasks.indexOf(task);
  88586. if (index > -1) {
  88587. _this._tasks.splice(index, 1);
  88588. }
  88589. });
  88590. }
  88591. if (this.onProgress) {
  88592. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88593. }
  88594. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88595. }
  88596. catch (e) {
  88597. BABYLON.Tools.Error("Error running progress callbacks.");
  88598. console.log(e);
  88599. }
  88600. if (this._waitingTasksCount === 0) {
  88601. try {
  88602. if (this.onFinish) {
  88603. this.onFinish(this._tasks);
  88604. }
  88605. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88606. }
  88607. catch (e) {
  88608. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88609. console.log(e);
  88610. }
  88611. this._isLoading = false;
  88612. this._scene.getEngine().hideLoadingUI();
  88613. }
  88614. };
  88615. AssetsManager.prototype._runTask = function (task) {
  88616. var _this = this;
  88617. var done = function () {
  88618. try {
  88619. if (_this.onTaskSuccess) {
  88620. _this.onTaskSuccess(task);
  88621. }
  88622. _this.onTaskSuccessObservable.notifyObservers(task);
  88623. _this._decreaseWaitingTasksCount(task);
  88624. }
  88625. catch (e) {
  88626. error("Error executing task success callbacks", e);
  88627. }
  88628. };
  88629. var error = function (message, exception) {
  88630. task._setErrorObject(message, exception);
  88631. if (_this.onTaskError) {
  88632. _this.onTaskError(task);
  88633. }
  88634. _this.onTaskErrorObservable.notifyObservers(task);
  88635. _this._decreaseWaitingTasksCount(task);
  88636. };
  88637. task.run(this._scene, done, error);
  88638. };
  88639. /**
  88640. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88641. * @return the current instance of the {BABYLON.AssetsManager}
  88642. */
  88643. AssetsManager.prototype.reset = function () {
  88644. this._isLoading = false;
  88645. this._tasks = new Array();
  88646. return this;
  88647. };
  88648. /**
  88649. * Start the loading process
  88650. * @return the current instance of the {BABYLON.AssetsManager}
  88651. */
  88652. AssetsManager.prototype.load = function () {
  88653. if (this._isLoading) {
  88654. return this;
  88655. }
  88656. this._isLoading = true;
  88657. this._waitingTasksCount = this._tasks.length;
  88658. this._totalTasksCount = this._tasks.length;
  88659. if (this._waitingTasksCount === 0) {
  88660. this._isLoading = false;
  88661. if (this.onFinish) {
  88662. this.onFinish(this._tasks);
  88663. }
  88664. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88665. return this;
  88666. }
  88667. if (this.useDefaultLoadingScreen) {
  88668. this._scene.getEngine().displayLoadingUI();
  88669. }
  88670. for (var index = 0; index < this._tasks.length; index++) {
  88671. var task = this._tasks[index];
  88672. this._runTask(task);
  88673. }
  88674. return this;
  88675. };
  88676. return AssetsManager;
  88677. }());
  88678. BABYLON.AssetsManager = AssetsManager;
  88679. })(BABYLON || (BABYLON = {}));
  88680. //# sourceMappingURL=babylon.assetsManager.js.map
  88681. "use strict";
  88682. var BABYLON;
  88683. (function (BABYLON) {
  88684. var serializedGeometries = [];
  88685. var serializeGeometry = function (geometry, serializationGeometries) {
  88686. if (serializedGeometries[geometry.id]) {
  88687. return;
  88688. }
  88689. if (geometry.doNotSerialize) {
  88690. return;
  88691. }
  88692. if (geometry instanceof BABYLON.BoxGeometry) {
  88693. serializationGeometries.boxes.push(geometry.serialize());
  88694. }
  88695. else if (geometry instanceof BABYLON.SphereGeometry) {
  88696. serializationGeometries.spheres.push(geometry.serialize());
  88697. }
  88698. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88699. serializationGeometries.cylinders.push(geometry.serialize());
  88700. }
  88701. else if (geometry instanceof BABYLON.TorusGeometry) {
  88702. serializationGeometries.toruses.push(geometry.serialize());
  88703. }
  88704. else if (geometry instanceof BABYLON.GroundGeometry) {
  88705. serializationGeometries.grounds.push(geometry.serialize());
  88706. }
  88707. else if (geometry instanceof BABYLON.Plane) {
  88708. serializationGeometries.planes.push(geometry.serialize());
  88709. }
  88710. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88711. serializationGeometries.torusKnots.push(geometry.serialize());
  88712. }
  88713. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88714. throw new Error("Unknown primitive type");
  88715. }
  88716. else {
  88717. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88718. }
  88719. serializedGeometries[geometry.id] = true;
  88720. };
  88721. var serializeMesh = function (mesh, serializationScene) {
  88722. var serializationObject = {};
  88723. // Geometry
  88724. var geometry = mesh._geometry;
  88725. if (geometry) {
  88726. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88727. // 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
  88728. serializeGeometry(geometry, serializationScene.geometries);
  88729. }
  88730. }
  88731. // Custom
  88732. if (mesh.serialize) {
  88733. mesh.serialize(serializationObject);
  88734. }
  88735. return serializationObject;
  88736. };
  88737. var finalizeSingleMesh = function (mesh, serializationObject) {
  88738. //only works if the mesh is already loaded
  88739. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88740. //serialize material
  88741. if (mesh.material) {
  88742. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88743. serializationObject.materials = serializationObject.materials || [];
  88744. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88745. serializationObject.materials.push(mesh.material.serialize());
  88746. }
  88747. }
  88748. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88749. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88750. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88751. serializationObject.multiMaterials.push(mesh.material.serialize());
  88752. }
  88753. }
  88754. }
  88755. //serialize geometry
  88756. var geometry = mesh._geometry;
  88757. if (geometry) {
  88758. if (!serializationObject.geometries) {
  88759. serializationObject.geometries = {};
  88760. serializationObject.geometries.boxes = [];
  88761. serializationObject.geometries.spheres = [];
  88762. serializationObject.geometries.cylinders = [];
  88763. serializationObject.geometries.toruses = [];
  88764. serializationObject.geometries.grounds = [];
  88765. serializationObject.geometries.planes = [];
  88766. serializationObject.geometries.torusKnots = [];
  88767. serializationObject.geometries.vertexData = [];
  88768. }
  88769. serializeGeometry(geometry, serializationObject.geometries);
  88770. }
  88771. // Skeletons
  88772. if (mesh.skeleton) {
  88773. serializationObject.skeletons = serializationObject.skeletons || [];
  88774. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88775. }
  88776. //serialize the actual mesh
  88777. serializationObject.meshes = serializationObject.meshes || [];
  88778. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88779. }
  88780. };
  88781. var SceneSerializer = /** @class */ (function () {
  88782. function SceneSerializer() {
  88783. }
  88784. SceneSerializer.ClearCache = function () {
  88785. serializedGeometries = [];
  88786. };
  88787. SceneSerializer.Serialize = function (scene) {
  88788. var serializationObject = {};
  88789. SceneSerializer.ClearCache();
  88790. // Scene
  88791. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88792. serializationObject.autoClear = scene.autoClear;
  88793. serializationObject.clearColor = scene.clearColor.asArray();
  88794. serializationObject.ambientColor = scene.ambientColor.asArray();
  88795. serializationObject.gravity = scene.gravity.asArray();
  88796. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88797. serializationObject.workerCollisions = scene.workerCollisions;
  88798. // Fog
  88799. if (scene.fogMode && scene.fogMode !== 0) {
  88800. serializationObject.fogMode = scene.fogMode;
  88801. serializationObject.fogColor = scene.fogColor.asArray();
  88802. serializationObject.fogStart = scene.fogStart;
  88803. serializationObject.fogEnd = scene.fogEnd;
  88804. serializationObject.fogDensity = scene.fogDensity;
  88805. }
  88806. //Physics
  88807. if (scene.isPhysicsEnabled()) {
  88808. var physicEngine = scene.getPhysicsEngine();
  88809. if (physicEngine) {
  88810. serializationObject.physicsEnabled = true;
  88811. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88812. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88813. }
  88814. }
  88815. // Metadata
  88816. if (scene.metadata) {
  88817. serializationObject.metadata = scene.metadata;
  88818. }
  88819. // Morph targets
  88820. serializationObject.morphTargetManagers = [];
  88821. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88822. var abstractMesh = _a[_i];
  88823. var manager = abstractMesh.morphTargetManager;
  88824. if (manager) {
  88825. serializationObject.morphTargetManagers.push(manager.serialize());
  88826. }
  88827. }
  88828. // Lights
  88829. serializationObject.lights = [];
  88830. var index;
  88831. var light;
  88832. for (index = 0; index < scene.lights.length; index++) {
  88833. light = scene.lights[index];
  88834. if (!light.doNotSerialize) {
  88835. serializationObject.lights.push(light.serialize());
  88836. }
  88837. }
  88838. // Cameras
  88839. serializationObject.cameras = [];
  88840. for (index = 0; index < scene.cameras.length; index++) {
  88841. var camera = scene.cameras[index];
  88842. if (!camera.doNotSerialize) {
  88843. serializationObject.cameras.push(camera.serialize());
  88844. }
  88845. }
  88846. if (scene.activeCamera) {
  88847. serializationObject.activeCameraID = scene.activeCamera.id;
  88848. }
  88849. // Animations
  88850. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88851. // Materials
  88852. serializationObject.materials = [];
  88853. serializationObject.multiMaterials = [];
  88854. var material;
  88855. for (index = 0; index < scene.materials.length; index++) {
  88856. material = scene.materials[index];
  88857. if (!material.doNotSerialize) {
  88858. serializationObject.materials.push(material.serialize());
  88859. }
  88860. }
  88861. // MultiMaterials
  88862. serializationObject.multiMaterials = [];
  88863. for (index = 0; index < scene.multiMaterials.length; index++) {
  88864. var multiMaterial = scene.multiMaterials[index];
  88865. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88866. }
  88867. // Environment texture
  88868. if (scene.environmentTexture) {
  88869. serializationObject.environmentTexture = scene.environmentTexture.name;
  88870. }
  88871. // Skeletons
  88872. serializationObject.skeletons = [];
  88873. for (index = 0; index < scene.skeletons.length; index++) {
  88874. var skeleton = scene.skeletons[index];
  88875. if (!skeleton.doNotSerialize) {
  88876. serializationObject.skeletons.push(skeleton.serialize());
  88877. }
  88878. }
  88879. // Transform nodes
  88880. serializationObject.transformNodes = [];
  88881. for (index = 0; index < scene.transformNodes.length; index++) {
  88882. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88883. }
  88884. // Geometries
  88885. serializationObject.geometries = {};
  88886. serializationObject.geometries.boxes = [];
  88887. serializationObject.geometries.spheres = [];
  88888. serializationObject.geometries.cylinders = [];
  88889. serializationObject.geometries.toruses = [];
  88890. serializationObject.geometries.grounds = [];
  88891. serializationObject.geometries.planes = [];
  88892. serializationObject.geometries.torusKnots = [];
  88893. serializationObject.geometries.vertexData = [];
  88894. serializedGeometries = [];
  88895. var geometries = scene.getGeometries();
  88896. for (index = 0; index < geometries.length; index++) {
  88897. var geometry = geometries[index];
  88898. if (geometry.isReady()) {
  88899. serializeGeometry(geometry, serializationObject.geometries);
  88900. }
  88901. }
  88902. // Meshes
  88903. serializationObject.meshes = [];
  88904. for (index = 0; index < scene.meshes.length; index++) {
  88905. var abstractMesh = scene.meshes[index];
  88906. if (abstractMesh instanceof BABYLON.Mesh) {
  88907. var mesh = abstractMesh;
  88908. if (!mesh.doNotSerialize) {
  88909. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88910. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88911. }
  88912. }
  88913. }
  88914. }
  88915. // Particles Systems
  88916. serializationObject.particleSystems = [];
  88917. for (index = 0; index < scene.particleSystems.length; index++) {
  88918. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88919. }
  88920. // Lens flares
  88921. serializationObject.lensFlareSystems = [];
  88922. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88923. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88924. }
  88925. // Shadows
  88926. serializationObject.shadowGenerators = [];
  88927. for (index = 0; index < scene.lights.length; index++) {
  88928. light = scene.lights[index];
  88929. var shadowGenerator = light.getShadowGenerator();
  88930. if (shadowGenerator) {
  88931. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88932. }
  88933. }
  88934. // Action Manager
  88935. if (scene.actionManager) {
  88936. serializationObject.actions = scene.actionManager.serialize("scene");
  88937. }
  88938. // Audio
  88939. serializationObject.sounds = [];
  88940. for (index = 0; index < scene.soundTracks.length; index++) {
  88941. var soundtrack = scene.soundTracks[index];
  88942. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88943. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88944. }
  88945. }
  88946. return serializationObject;
  88947. };
  88948. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88949. if (withParents === void 0) { withParents = false; }
  88950. if (withChildren === void 0) { withChildren = false; }
  88951. var serializationObject = {};
  88952. SceneSerializer.ClearCache();
  88953. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88954. if (withParents || withChildren) {
  88955. //deliberate for loop! not for each, appended should be processed as well.
  88956. for (var i = 0; i < toSerialize.length; ++i) {
  88957. if (withChildren) {
  88958. toSerialize[i].getDescendants().forEach(function (node) {
  88959. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88960. toSerialize.push(node);
  88961. }
  88962. });
  88963. }
  88964. //make sure the array doesn't contain the object already
  88965. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88966. toSerialize.push(toSerialize[i].parent);
  88967. }
  88968. }
  88969. }
  88970. toSerialize.forEach(function (mesh) {
  88971. finalizeSingleMesh(mesh, serializationObject);
  88972. });
  88973. return serializationObject;
  88974. };
  88975. return SceneSerializer;
  88976. }());
  88977. BABYLON.SceneSerializer = SceneSerializer;
  88978. })(BABYLON || (BABYLON = {}));
  88979. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88980. "use strict";
  88981. var BABYLON;
  88982. (function (BABYLON) {
  88983. var ReflectionProbe = /** @class */ (function () {
  88984. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88986. var _this = this;
  88987. this.name = name;
  88988. this._viewMatrix = BABYLON.Matrix.Identity();
  88989. this._target = BABYLON.Vector3.Zero();
  88990. this._add = BABYLON.Vector3.Zero();
  88991. this._invertYAxis = false;
  88992. this.position = BABYLON.Vector3.Zero();
  88993. this._scene = scene;
  88994. this._scene.reflectionProbes.push(this);
  88995. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88996. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88997. switch (faceIndex) {
  88998. case 0:
  88999. _this._add.copyFromFloats(1, 0, 0);
  89000. break;
  89001. case 1:
  89002. _this._add.copyFromFloats(-1, 0, 0);
  89003. break;
  89004. case 2:
  89005. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  89006. break;
  89007. case 3:
  89008. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  89009. break;
  89010. case 4:
  89011. _this._add.copyFromFloats(0, 0, 1);
  89012. break;
  89013. case 5:
  89014. _this._add.copyFromFloats(0, 0, -1);
  89015. break;
  89016. }
  89017. if (_this._attachedMesh) {
  89018. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  89019. }
  89020. _this.position.addToRef(_this._add, _this._target);
  89021. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  89022. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  89023. scene._forcedViewPosition = _this.position;
  89024. });
  89025. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  89026. scene._forcedViewPosition = null;
  89027. scene.updateTransformMatrix(true);
  89028. });
  89029. if (scene.activeCamera) {
  89030. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  89031. }
  89032. }
  89033. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  89034. get: function () {
  89035. return this._renderTargetTexture.samples;
  89036. },
  89037. set: function (value) {
  89038. this._renderTargetTexture.samples = value;
  89039. },
  89040. enumerable: true,
  89041. configurable: true
  89042. });
  89043. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  89044. get: function () {
  89045. return this._renderTargetTexture.refreshRate;
  89046. },
  89047. set: function (value) {
  89048. this._renderTargetTexture.refreshRate = value;
  89049. },
  89050. enumerable: true,
  89051. configurable: true
  89052. });
  89053. ReflectionProbe.prototype.getScene = function () {
  89054. return this._scene;
  89055. };
  89056. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  89057. get: function () {
  89058. return this._renderTargetTexture;
  89059. },
  89060. enumerable: true,
  89061. configurable: true
  89062. });
  89063. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  89064. get: function () {
  89065. return this._renderTargetTexture.renderList;
  89066. },
  89067. enumerable: true,
  89068. configurable: true
  89069. });
  89070. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  89071. this._attachedMesh = mesh;
  89072. };
  89073. /**
  89074. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  89075. *
  89076. * @param renderingGroupId The rendering group id corresponding to its index
  89077. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  89078. */
  89079. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  89080. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  89081. };
  89082. ReflectionProbe.prototype.dispose = function () {
  89083. var index = this._scene.reflectionProbes.indexOf(this);
  89084. if (index !== -1) {
  89085. // Remove from the scene if found
  89086. this._scene.reflectionProbes.splice(index, 1);
  89087. }
  89088. if (this._renderTargetTexture) {
  89089. this._renderTargetTexture.dispose();
  89090. this._renderTargetTexture = null;
  89091. }
  89092. };
  89093. return ReflectionProbe;
  89094. }());
  89095. BABYLON.ReflectionProbe = ReflectionProbe;
  89096. })(BABYLON || (BABYLON = {}));
  89097. //# sourceMappingURL=babylon.reflectionProbe.js.map
  89098. "use strict";
  89099. var BABYLON;
  89100. (function (BABYLON) {
  89101. var Layer = /** @class */ (function () {
  89102. function Layer(name, imgUrl, scene, isBackground, color) {
  89103. this.name = name;
  89104. this.scale = new BABYLON.Vector2(1, 1);
  89105. this.offset = new BABYLON.Vector2(0, 0);
  89106. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  89107. this.layerMask = 0x0FFFFFFF;
  89108. this._vertexBuffers = {};
  89109. // Events
  89110. /**
  89111. * An event triggered when the layer is disposed.
  89112. * @type {BABYLON.Observable}
  89113. */
  89114. this.onDisposeObservable = new BABYLON.Observable();
  89115. /**
  89116. * An event triggered before rendering the scene
  89117. * @type {BABYLON.Observable}
  89118. */
  89119. this.onBeforeRenderObservable = new BABYLON.Observable();
  89120. /**
  89121. * An event triggered after rendering the scene
  89122. * @type {BABYLON.Observable}
  89123. */
  89124. this.onAfterRenderObservable = new BABYLON.Observable();
  89125. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  89126. this.isBackground = isBackground === undefined ? true : isBackground;
  89127. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  89128. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  89129. this._scene.layers.push(this);
  89130. var engine = this._scene.getEngine();
  89131. // VBO
  89132. var vertices = [];
  89133. vertices.push(1, 1);
  89134. vertices.push(-1, 1);
  89135. vertices.push(-1, -1);
  89136. vertices.push(1, -1);
  89137. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  89138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  89139. this._createIndexBuffer();
  89140. // Effects
  89141. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  89142. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  89143. }
  89144. Object.defineProperty(Layer.prototype, "onDispose", {
  89145. set: function (callback) {
  89146. if (this._onDisposeObserver) {
  89147. this.onDisposeObservable.remove(this._onDisposeObserver);
  89148. }
  89149. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  89150. },
  89151. enumerable: true,
  89152. configurable: true
  89153. });
  89154. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  89155. set: function (callback) {
  89156. if (this._onBeforeRenderObserver) {
  89157. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  89158. }
  89159. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  89160. },
  89161. enumerable: true,
  89162. configurable: true
  89163. });
  89164. Object.defineProperty(Layer.prototype, "onAfterRender", {
  89165. set: function (callback) {
  89166. if (this._onAfterRenderObserver) {
  89167. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  89168. }
  89169. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  89170. },
  89171. enumerable: true,
  89172. configurable: true
  89173. });
  89174. Layer.prototype._createIndexBuffer = function () {
  89175. var engine = this._scene.getEngine();
  89176. // Indices
  89177. var indices = [];
  89178. indices.push(0);
  89179. indices.push(1);
  89180. indices.push(2);
  89181. indices.push(0);
  89182. indices.push(2);
  89183. indices.push(3);
  89184. this._indexBuffer = engine.createIndexBuffer(indices);
  89185. };
  89186. Layer.prototype._rebuild = function () {
  89187. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89188. if (vb) {
  89189. vb._rebuild();
  89190. }
  89191. this._createIndexBuffer();
  89192. };
  89193. Layer.prototype.render = function () {
  89194. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  89195. // Check
  89196. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  89197. return;
  89198. var engine = this._scene.getEngine();
  89199. this.onBeforeRenderObservable.notifyObservers(this);
  89200. // Render
  89201. engine.enableEffect(currentEffect);
  89202. engine.setState(false);
  89203. // Texture
  89204. currentEffect.setTexture("textureSampler", this.texture);
  89205. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  89206. // Color
  89207. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  89208. // Scale / offset
  89209. currentEffect.setVector2("offset", this.offset);
  89210. currentEffect.setVector2("scale", this.scale);
  89211. // VBOs
  89212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  89213. // Draw order
  89214. if (!this.alphaTest) {
  89215. engine.setAlphaMode(this.alphaBlendingMode);
  89216. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89217. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89218. }
  89219. else {
  89220. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  89221. }
  89222. this.onAfterRenderObservable.notifyObservers(this);
  89223. };
  89224. Layer.prototype.dispose = function () {
  89225. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  89226. if (vertexBuffer) {
  89227. vertexBuffer.dispose();
  89228. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  89229. }
  89230. if (this._indexBuffer) {
  89231. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  89232. this._indexBuffer = null;
  89233. }
  89234. if (this.texture) {
  89235. this.texture.dispose();
  89236. this.texture = null;
  89237. }
  89238. // Remove from scene
  89239. var index = this._scene.layers.indexOf(this);
  89240. this._scene.layers.splice(index, 1);
  89241. // Callback
  89242. this.onDisposeObservable.notifyObservers(this);
  89243. this.onDisposeObservable.clear();
  89244. this.onAfterRenderObservable.clear();
  89245. this.onBeforeRenderObservable.clear();
  89246. };
  89247. return Layer;
  89248. }());
  89249. BABYLON.Layer = Layer;
  89250. })(BABYLON || (BABYLON = {}));
  89251. //# sourceMappingURL=babylon.layer.js.map
  89252. "use strict";
  89253. var BABYLON;
  89254. (function (BABYLON) {
  89255. var TextureTools = /** @class */ (function () {
  89256. function TextureTools() {
  89257. }
  89258. /**
  89259. * Uses the GPU to create a copy texture rescaled at a given size
  89260. * @param texture Texture to copy from
  89261. * @param width Desired width
  89262. * @param height Desired height
  89263. * @return Generated texture
  89264. */
  89265. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  89266. if (useBilinearMode === void 0) { useBilinearMode = true; }
  89267. var scene = texture.getScene();
  89268. var engine = scene.getEngine();
  89269. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  89270. rtt.wrapU = texture.wrapU;
  89271. rtt.wrapV = texture.wrapV;
  89272. rtt.uOffset = texture.uOffset;
  89273. rtt.vOffset = texture.vOffset;
  89274. rtt.uScale = texture.uScale;
  89275. rtt.vScale = texture.vScale;
  89276. rtt.uAng = texture.uAng;
  89277. rtt.vAng = texture.vAng;
  89278. rtt.wAng = texture.wAng;
  89279. rtt.coordinatesIndex = texture.coordinatesIndex;
  89280. rtt.level = texture.level;
  89281. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  89282. rtt._texture.isReady = false;
  89283. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89284. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89285. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89286. passPostProcess.getEffect().executeWhenCompiled(function () {
  89287. passPostProcess.onApply = function (effect) {
  89288. effect.setTexture("textureSampler", texture);
  89289. };
  89290. var internalTexture = rtt.getInternalTexture();
  89291. if (internalTexture) {
  89292. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  89293. engine.unBindFramebuffer(internalTexture);
  89294. rtt.disposeFramebufferObjects();
  89295. passPostProcess.dispose();
  89296. internalTexture.isReady = true;
  89297. }
  89298. });
  89299. return rtt;
  89300. };
  89301. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  89302. if (!scene._environmentBRDFTexture) {
  89303. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  89304. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89305. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89306. scene._environmentBRDFTexture = texture;
  89307. }
  89308. return scene._environmentBRDFTexture;
  89309. };
  89310. 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=";
  89311. return TextureTools;
  89312. }());
  89313. BABYLON.TextureTools = TextureTools;
  89314. })(BABYLON || (BABYLON = {}));
  89315. //# sourceMappingURL=babylon.textureTools.js.map
  89316. "use strict";
  89317. var BABYLON;
  89318. (function (BABYLON) {
  89319. var FramingBehavior = /** @class */ (function () {
  89320. function FramingBehavior() {
  89321. this._mode = FramingBehavior.FitFrustumSidesMode;
  89322. this._radiusScale = 1.0;
  89323. this._positionScale = 0.5;
  89324. this._defaultElevation = 0.3;
  89325. this._elevationReturnTime = 1500;
  89326. this._elevationReturnWaitTime = 1000;
  89327. this._zoomStopsAnimation = false;
  89328. this._framingTime = 1500;
  89329. this._isPointerDown = false;
  89330. this._lastInteractionTime = -Infinity;
  89331. // Framing control
  89332. this._animatables = new Array();
  89333. this._betaIsAnimating = false;
  89334. }
  89335. Object.defineProperty(FramingBehavior.prototype, "name", {
  89336. get: function () {
  89337. return "Framing";
  89338. },
  89339. enumerable: true,
  89340. configurable: true
  89341. });
  89342. Object.defineProperty(FramingBehavior.prototype, "mode", {
  89343. /**
  89344. * Gets current mode used by the behavior.
  89345. */
  89346. get: function () {
  89347. return this._mode;
  89348. },
  89349. /**
  89350. * Sets the current mode used by the behavior
  89351. */
  89352. set: function (mode) {
  89353. this._mode = mode;
  89354. },
  89355. enumerable: true,
  89356. configurable: true
  89357. });
  89358. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  89359. /**
  89360. * Gets the scale applied to the radius
  89361. */
  89362. get: function () {
  89363. return this._radiusScale;
  89364. },
  89365. /**
  89366. * Sets the scale applied to the radius (1 by default)
  89367. */
  89368. set: function (radius) {
  89369. this._radiusScale = radius;
  89370. },
  89371. enumerable: true,
  89372. configurable: true
  89373. });
  89374. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  89375. /**
  89376. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89377. */
  89378. get: function () {
  89379. return this._positionScale;
  89380. },
  89381. /**
  89382. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  89383. */
  89384. set: function (scale) {
  89385. this._positionScale = scale;
  89386. },
  89387. enumerable: true,
  89388. configurable: true
  89389. });
  89390. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  89391. /**
  89392. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89393. * behaviour is triggered, in radians.
  89394. */
  89395. get: function () {
  89396. return this._defaultElevation;
  89397. },
  89398. /**
  89399. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  89400. * behaviour is triggered, in radians.
  89401. */
  89402. set: function (elevation) {
  89403. this._defaultElevation = elevation;
  89404. },
  89405. enumerable: true,
  89406. configurable: true
  89407. });
  89408. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  89409. /**
  89410. * Gets the time (in milliseconds) taken to return to the default beta position.
  89411. * Negative value indicates camera should not return to default.
  89412. */
  89413. get: function () {
  89414. return this._elevationReturnTime;
  89415. },
  89416. /**
  89417. * Sets the time (in milliseconds) taken to return to the default beta position.
  89418. * Negative value indicates camera should not return to default.
  89419. */
  89420. set: function (speed) {
  89421. this._elevationReturnTime = speed;
  89422. },
  89423. enumerable: true,
  89424. configurable: true
  89425. });
  89426. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  89427. /**
  89428. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89429. */
  89430. get: function () {
  89431. return this._elevationReturnWaitTime;
  89432. },
  89433. /**
  89434. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  89435. */
  89436. set: function (time) {
  89437. this._elevationReturnWaitTime = time;
  89438. },
  89439. enumerable: true,
  89440. configurable: true
  89441. });
  89442. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  89443. /**
  89444. * Gets the flag that indicates if user zooming should stop animation.
  89445. */
  89446. get: function () {
  89447. return this._zoomStopsAnimation;
  89448. },
  89449. /**
  89450. * Sets the flag that indicates if user zooming should stop animation.
  89451. */
  89452. set: function (flag) {
  89453. this._zoomStopsAnimation = flag;
  89454. },
  89455. enumerable: true,
  89456. configurable: true
  89457. });
  89458. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  89459. /**
  89460. * Gets the transition time when framing the mesh, in milliseconds
  89461. */
  89462. get: function () {
  89463. return this._framingTime;
  89464. },
  89465. /**
  89466. * Sets the transition time when framing the mesh, in milliseconds
  89467. */
  89468. set: function (time) {
  89469. this._framingTime = time;
  89470. },
  89471. enumerable: true,
  89472. configurable: true
  89473. });
  89474. FramingBehavior.prototype.init = function () {
  89475. // Do notihng
  89476. };
  89477. FramingBehavior.prototype.attach = function (camera) {
  89478. var _this = this;
  89479. this._attachedCamera = camera;
  89480. var scene = this._attachedCamera.getScene();
  89481. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  89482. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89483. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89484. _this._isPointerDown = true;
  89485. return;
  89486. }
  89487. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89488. _this._isPointerDown = false;
  89489. }
  89490. });
  89491. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89492. if (mesh) {
  89493. _this.zoomOnMesh(mesh);
  89494. }
  89495. });
  89496. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89497. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89498. _this._applyUserInteraction();
  89499. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  89500. // back to the default position after a given timeout
  89501. _this._maintainCameraAboveGround();
  89502. });
  89503. };
  89504. FramingBehavior.prototype.detach = function () {
  89505. if (!this._attachedCamera) {
  89506. return;
  89507. }
  89508. var scene = this._attachedCamera.getScene();
  89509. if (this._onPrePointerObservableObserver) {
  89510. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89511. }
  89512. if (this._onAfterCheckInputsObserver) {
  89513. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89514. }
  89515. if (this._onMeshTargetChangedObserver) {
  89516. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89517. }
  89518. this._attachedCamera = null;
  89519. };
  89520. /**
  89521. * Targets the given mesh and updates zoom level accordingly.
  89522. * @param mesh The mesh to target.
  89523. * @param radius Optional. If a cached radius position already exists, overrides default.
  89524. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89525. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89526. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89527. */
  89528. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89529. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89530. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89531. mesh.computeWorldMatrix(true);
  89532. var boundingBox = mesh.getBoundingInfo().boundingBox;
  89533. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  89534. };
  89535. /**
  89536. * Targets the given mesh with its children and updates zoom level accordingly.
  89537. * @param mesh The mesh to target.
  89538. * @param radius Optional. If a cached radius position already exists, overrides default.
  89539. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89540. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89541. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89542. */
  89543. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  89544. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89545. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89546. mesh.computeWorldMatrix(true);
  89547. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  89548. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  89549. };
  89550. /**
  89551. * Targets the given meshes with their children and updates zoom level accordingly.
  89552. * @param meshes The mesh to target.
  89553. * @param radius Optional. If a cached radius position already exists, overrides default.
  89554. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89555. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89556. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89557. */
  89558. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89559. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89560. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89561. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89562. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89563. for (var i = 0; i < meshes.length; i++) {
  89564. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89565. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89566. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89567. }
  89568. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89569. };
  89570. /**
  89571. * Targets the given mesh and updates zoom level accordingly.
  89572. * @param mesh The mesh to target.
  89573. * @param radius Optional. If a cached radius position already exists, overrides default.
  89574. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89575. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89576. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89577. */
  89578. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89579. var _this = this;
  89580. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89581. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89582. var zoomTarget;
  89583. if (!this._attachedCamera) {
  89584. return;
  89585. }
  89586. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89587. var bottom = minimumWorld.y;
  89588. var top = maximumWorld.y;
  89589. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89590. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89591. if (focusOnOriginXZ) {
  89592. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89593. }
  89594. else {
  89595. var centerWorld = minimumWorld.add(radiusWorld);
  89596. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89597. }
  89598. if (!this._vectorTransition) {
  89599. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89600. }
  89601. this._betaIsAnimating = true;
  89602. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89603. if (animatable) {
  89604. this._animatables.push(animatable);
  89605. }
  89606. // sets the radius and lower radius bounds
  89607. // Small delta ensures camera is not always at lower zoom limit.
  89608. var radius = 0;
  89609. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89610. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89611. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89612. radius = position;
  89613. }
  89614. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89615. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89616. if (this._attachedCamera.lowerRadiusLimit === null) {
  89617. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89618. }
  89619. }
  89620. // Set sensibilities
  89621. var extend = maximumWorld.subtract(minimumWorld).length();
  89622. this._attachedCamera.panningSensibility = 5000 / extend;
  89623. this._attachedCamera.wheelPrecision = 100 / radius;
  89624. // transition to new radius
  89625. if (!this._radiusTransition) {
  89626. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89627. }
  89628. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89629. _this.stopAllAnimations();
  89630. if (onAnimationEnd) {
  89631. onAnimationEnd();
  89632. }
  89633. if (_this._attachedCamera) {
  89634. _this._attachedCamera.storeState();
  89635. }
  89636. });
  89637. if (animatable) {
  89638. this._animatables.push(animatable);
  89639. }
  89640. };
  89641. /**
  89642. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89643. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89644. * frustum width.
  89645. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89646. * to fully enclose the mesh in the viewing frustum.
  89647. */
  89648. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89649. var size = maximumWorld.subtract(minimumWorld);
  89650. var boxVectorGlobalDiagonal = size.length();
  89651. var frustumSlope = this._getFrustumSlope();
  89652. // Formula for setting distance
  89653. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89654. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89655. // Horizon distance
  89656. var radius = radiusWithoutFraming * this._radiusScale;
  89657. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89658. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89659. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89660. var camera = this._attachedCamera;
  89661. if (!camera) {
  89662. return 0;
  89663. }
  89664. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89665. // Don't exceed the requested limit
  89666. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89667. }
  89668. // Don't exceed the upper radius limit
  89669. if (camera.upperRadiusLimit) {
  89670. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89671. }
  89672. return distance;
  89673. };
  89674. /**
  89675. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89676. * is automatically returned to its default position (expected to be above ground plane).
  89677. */
  89678. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89679. var _this = this;
  89680. if (this._elevationReturnTime < 0) {
  89681. return;
  89682. }
  89683. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89684. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89685. var limitBeta = Math.PI * 0.5;
  89686. // Bring the camera back up if below the ground plane
  89687. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89688. this._betaIsAnimating = true;
  89689. //Transition to new position
  89690. this.stopAllAnimations();
  89691. if (!this._betaTransition) {
  89692. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89693. }
  89694. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89695. _this._clearAnimationLocks();
  89696. _this.stopAllAnimations();
  89697. });
  89698. if (animatabe) {
  89699. this._animatables.push(animatabe);
  89700. }
  89701. }
  89702. };
  89703. /**
  89704. * Returns the frustum slope based on the canvas ratio and camera FOV
  89705. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89706. */
  89707. FramingBehavior.prototype._getFrustumSlope = function () {
  89708. // Calculate the viewport ratio
  89709. // Aspect Ratio is Height/Width.
  89710. var camera = this._attachedCamera;
  89711. if (!camera) {
  89712. return BABYLON.Vector2.Zero();
  89713. }
  89714. var engine = camera.getScene().getEngine();
  89715. var aspectRatio = engine.getAspectRatio(camera);
  89716. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89717. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89718. var frustumSlopeY = Math.tan(camera.fov / 2);
  89719. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89720. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89721. // along the forward vector.
  89722. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89723. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89724. };
  89725. /**
  89726. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89727. */
  89728. FramingBehavior.prototype._clearAnimationLocks = function () {
  89729. this._betaIsAnimating = false;
  89730. };
  89731. /**
  89732. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89733. */
  89734. FramingBehavior.prototype._applyUserInteraction = function () {
  89735. if (this.isUserIsMoving) {
  89736. this._lastInteractionTime = BABYLON.Tools.Now;
  89737. this.stopAllAnimations();
  89738. this._clearAnimationLocks();
  89739. }
  89740. };
  89741. /**
  89742. * Stops and removes all animations that have been applied to the camera
  89743. */
  89744. FramingBehavior.prototype.stopAllAnimations = function () {
  89745. if (this._attachedCamera) {
  89746. this._attachedCamera.animations = [];
  89747. }
  89748. while (this._animatables.length) {
  89749. if (this._animatables[0]) {
  89750. this._animatables[0].onAnimationEnd = null;
  89751. this._animatables[0].stop();
  89752. }
  89753. this._animatables.shift();
  89754. }
  89755. };
  89756. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89757. /**
  89758. * Gets a value indicating if the user is moving the camera
  89759. */
  89760. get: function () {
  89761. if (!this._attachedCamera) {
  89762. return false;
  89763. }
  89764. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89765. this._attachedCamera.inertialBetaOffset !== 0 ||
  89766. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89767. this._attachedCamera.inertialPanningX !== 0 ||
  89768. this._attachedCamera.inertialPanningY !== 0 ||
  89769. this._isPointerDown;
  89770. },
  89771. enumerable: true,
  89772. configurable: true
  89773. });
  89774. /**
  89775. * The easing function used by animations
  89776. */
  89777. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89778. /**
  89779. * The easing mode used by animations
  89780. */
  89781. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89782. // Statics
  89783. /**
  89784. * The camera can move all the way towards the mesh.
  89785. */
  89786. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89787. /**
  89788. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89789. */
  89790. FramingBehavior.FitFrustumSidesMode = 1;
  89791. return FramingBehavior;
  89792. }());
  89793. BABYLON.FramingBehavior = FramingBehavior;
  89794. })(BABYLON || (BABYLON = {}));
  89795. //# sourceMappingURL=babylon.framingBehavior.js.map
  89796. "use strict";
  89797. var BABYLON;
  89798. (function (BABYLON) {
  89799. /**
  89800. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89801. */
  89802. var BouncingBehavior = /** @class */ (function () {
  89803. function BouncingBehavior() {
  89804. /**
  89805. * The duration of the animation, in milliseconds
  89806. */
  89807. this.transitionDuration = 450;
  89808. /**
  89809. * Length of the distance animated by the transition when lower radius is reached
  89810. */
  89811. this.lowerRadiusTransitionRange = 2;
  89812. /**
  89813. * Length of the distance animated by the transition when upper radius is reached
  89814. */
  89815. this.upperRadiusTransitionRange = -2;
  89816. this._autoTransitionRange = false;
  89817. // Animations
  89818. this._radiusIsAnimating = false;
  89819. this._radiusBounceTransition = null;
  89820. this._animatables = new Array();
  89821. }
  89822. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89823. get: function () {
  89824. return "Bouncing";
  89825. },
  89826. enumerable: true,
  89827. configurable: true
  89828. });
  89829. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89830. /**
  89831. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89832. */
  89833. get: function () {
  89834. return this._autoTransitionRange;
  89835. },
  89836. /**
  89837. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89838. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89839. */
  89840. set: function (value) {
  89841. var _this = this;
  89842. if (this._autoTransitionRange === value) {
  89843. return;
  89844. }
  89845. this._autoTransitionRange = value;
  89846. var camera = this._attachedCamera;
  89847. if (!camera) {
  89848. return;
  89849. }
  89850. if (value) {
  89851. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89852. if (!mesh) {
  89853. return;
  89854. }
  89855. mesh.computeWorldMatrix(true);
  89856. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89857. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89858. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89859. });
  89860. }
  89861. else if (this._onMeshTargetChangedObserver) {
  89862. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89863. }
  89864. },
  89865. enumerable: true,
  89866. configurable: true
  89867. });
  89868. BouncingBehavior.prototype.init = function () {
  89869. // Do notihng
  89870. };
  89871. BouncingBehavior.prototype.attach = function (camera) {
  89872. var _this = this;
  89873. this._attachedCamera = camera;
  89874. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89875. if (!_this._attachedCamera) {
  89876. return;
  89877. }
  89878. // Add the bounce animation to the lower radius limit
  89879. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89880. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89881. }
  89882. // Add the bounce animation to the upper radius limit
  89883. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89884. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89885. }
  89886. });
  89887. };
  89888. BouncingBehavior.prototype.detach = function () {
  89889. if (!this._attachedCamera) {
  89890. return;
  89891. }
  89892. if (this._onAfterCheckInputsObserver) {
  89893. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89894. }
  89895. if (this._onMeshTargetChangedObserver) {
  89896. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89897. }
  89898. this._attachedCamera = null;
  89899. };
  89900. /**
  89901. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89902. * @param radiusLimit The limit to check against.
  89903. * @return Bool to indicate if at limit.
  89904. */
  89905. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89906. if (!this._attachedCamera) {
  89907. return false;
  89908. }
  89909. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89910. return true;
  89911. }
  89912. return false;
  89913. };
  89914. /**
  89915. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89916. * @param radiusDelta The delta by which to animate to. Can be negative.
  89917. */
  89918. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89919. var _this = this;
  89920. if (!this._attachedCamera) {
  89921. return;
  89922. }
  89923. if (!this._radiusBounceTransition) {
  89924. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89925. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89926. }
  89927. // Prevent zoom until bounce has completed
  89928. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89929. this._attachedCamera.wheelPrecision = Infinity;
  89930. this._attachedCamera.inertialRadiusOffset = 0;
  89931. // Animate to the radius limit
  89932. this.stopAllAnimations();
  89933. this._radiusIsAnimating = true;
  89934. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89935. if (animatable) {
  89936. this._animatables.push(animatable);
  89937. }
  89938. };
  89939. /**
  89940. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89941. */
  89942. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89943. this._radiusIsAnimating = false;
  89944. if (this._attachedCamera) {
  89945. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89946. }
  89947. };
  89948. /**
  89949. * Stops and removes all animations that have been applied to the camera
  89950. */
  89951. BouncingBehavior.prototype.stopAllAnimations = function () {
  89952. if (this._attachedCamera) {
  89953. this._attachedCamera.animations = [];
  89954. }
  89955. while (this._animatables.length) {
  89956. this._animatables[0].onAnimationEnd = null;
  89957. this._animatables[0].stop();
  89958. this._animatables.shift();
  89959. }
  89960. };
  89961. /**
  89962. * The easing function used by animations
  89963. */
  89964. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89965. /**
  89966. * The easing mode used by animations
  89967. */
  89968. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89969. return BouncingBehavior;
  89970. }());
  89971. BABYLON.BouncingBehavior = BouncingBehavior;
  89972. })(BABYLON || (BABYLON = {}));
  89973. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89974. "use strict";
  89975. var BABYLON;
  89976. (function (BABYLON) {
  89977. var AutoRotationBehavior = /** @class */ (function () {
  89978. function AutoRotationBehavior() {
  89979. this._zoomStopsAnimation = false;
  89980. this._idleRotationSpeed = 0.05;
  89981. this._idleRotationWaitTime = 2000;
  89982. this._idleRotationSpinupTime = 2000;
  89983. this._isPointerDown = false;
  89984. this._lastFrameTime = null;
  89985. this._lastInteractionTime = -Infinity;
  89986. this._cameraRotationSpeed = 0;
  89987. this._lastFrameRadius = 0;
  89988. }
  89989. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89990. get: function () {
  89991. return "AutoRotation";
  89992. },
  89993. enumerable: true,
  89994. configurable: true
  89995. });
  89996. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89997. /**
  89998. * Gets the flag that indicates if user zooming should stop animation.
  89999. */
  90000. get: function () {
  90001. return this._zoomStopsAnimation;
  90002. },
  90003. /**
  90004. * Sets the flag that indicates if user zooming should stop animation.
  90005. */
  90006. set: function (flag) {
  90007. this._zoomStopsAnimation = flag;
  90008. },
  90009. enumerable: true,
  90010. configurable: true
  90011. });
  90012. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  90013. /**
  90014. * Gets the default speed at which the camera rotates around the model.
  90015. */
  90016. get: function () {
  90017. return this._idleRotationSpeed;
  90018. },
  90019. /**
  90020. * Sets the default speed at which the camera rotates around the model.
  90021. */
  90022. set: function (speed) {
  90023. this._idleRotationSpeed = speed;
  90024. },
  90025. enumerable: true,
  90026. configurable: true
  90027. });
  90028. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  90029. /**
  90030. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  90031. */
  90032. get: function () {
  90033. return this._idleRotationWaitTime;
  90034. },
  90035. /**
  90036. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  90037. */
  90038. set: function (time) {
  90039. this._idleRotationWaitTime = time;
  90040. },
  90041. enumerable: true,
  90042. configurable: true
  90043. });
  90044. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  90045. /**
  90046. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90047. */
  90048. get: function () {
  90049. return this._idleRotationSpinupTime;
  90050. },
  90051. /**
  90052. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  90053. */
  90054. set: function (time) {
  90055. this._idleRotationSpinupTime = time;
  90056. },
  90057. enumerable: true,
  90058. configurable: true
  90059. });
  90060. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  90061. /**
  90062. * Gets a value indicating if the camera is currently rotating because of this behavior
  90063. */
  90064. get: function () {
  90065. return Math.abs(this._cameraRotationSpeed) > 0;
  90066. },
  90067. enumerable: true,
  90068. configurable: true
  90069. });
  90070. AutoRotationBehavior.prototype.init = function () {
  90071. // Do notihng
  90072. };
  90073. AutoRotationBehavior.prototype.attach = function (camera) {
  90074. var _this = this;
  90075. this._attachedCamera = camera;
  90076. var scene = this._attachedCamera.getScene();
  90077. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  90078. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90079. _this._isPointerDown = true;
  90080. return;
  90081. }
  90082. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  90083. _this._isPointerDown = false;
  90084. }
  90085. });
  90086. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  90087. var now = BABYLON.Tools.Now;
  90088. var dt = 0;
  90089. if (_this._lastFrameTime != null) {
  90090. dt = now - _this._lastFrameTime;
  90091. }
  90092. _this._lastFrameTime = now;
  90093. // Stop the animation if there is user interaction and the animation should stop for this interaction
  90094. _this._applyUserInteraction();
  90095. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  90096. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  90097. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  90098. // Step camera rotation by rotation speed
  90099. if (_this._attachedCamera) {
  90100. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  90101. }
  90102. });
  90103. };
  90104. AutoRotationBehavior.prototype.detach = function () {
  90105. if (!this._attachedCamera) {
  90106. return;
  90107. }
  90108. var scene = this._attachedCamera.getScene();
  90109. if (this._onPrePointerObservableObserver) {
  90110. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  90111. }
  90112. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  90113. this._attachedCamera = null;
  90114. };
  90115. /**
  90116. * Returns true if user is scrolling.
  90117. * @return true if user is scrolling.
  90118. */
  90119. AutoRotationBehavior.prototype._userIsZooming = function () {
  90120. if (!this._attachedCamera) {
  90121. return false;
  90122. }
  90123. return this._attachedCamera.inertialRadiusOffset !== 0;
  90124. };
  90125. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  90126. if (!this._attachedCamera) {
  90127. return false;
  90128. }
  90129. var zoomHasHitLimit = false;
  90130. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  90131. zoomHasHitLimit = true;
  90132. }
  90133. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  90134. this._lastFrameRadius = this._attachedCamera.radius;
  90135. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  90136. };
  90137. /**
  90138. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  90139. */
  90140. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  90141. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  90142. this._lastInteractionTime = BABYLON.Tools.Now;
  90143. }
  90144. };
  90145. // Tools
  90146. AutoRotationBehavior.prototype._userIsMoving = function () {
  90147. if (!this._attachedCamera) {
  90148. return false;
  90149. }
  90150. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  90151. this._attachedCamera.inertialBetaOffset !== 0 ||
  90152. this._attachedCamera.inertialRadiusOffset !== 0 ||
  90153. this._attachedCamera.inertialPanningX !== 0 ||
  90154. this._attachedCamera.inertialPanningY !== 0 ||
  90155. this._isPointerDown;
  90156. };
  90157. return AutoRotationBehavior;
  90158. }());
  90159. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  90160. })(BABYLON || (BABYLON = {}));
  90161. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  90162. "use strict";
  90163. var BABYLON;
  90164. (function (BABYLON) {
  90165. var NullEngineOptions = /** @class */ (function () {
  90166. function NullEngineOptions() {
  90167. this.renderWidth = 512;
  90168. this.renderHeight = 256;
  90169. this.textureSize = 512;
  90170. this.deterministicLockstep = false;
  90171. this.lockstepMaxSteps = 4;
  90172. }
  90173. return NullEngineOptions;
  90174. }());
  90175. BABYLON.NullEngineOptions = NullEngineOptions;
  90176. /**
  90177. * The null engine class provides support for headless version of babylon.js.
  90178. * This can be used in server side scenario or for testing purposes
  90179. */
  90180. var NullEngine = /** @class */ (function (_super) {
  90181. __extends(NullEngine, _super);
  90182. function NullEngine(options) {
  90183. if (options === void 0) { options = new NullEngineOptions(); }
  90184. var _this = _super.call(this, null) || this;
  90185. if (options.deterministicLockstep === undefined) {
  90186. options.deterministicLockstep = false;
  90187. }
  90188. if (options.lockstepMaxSteps === undefined) {
  90189. options.lockstepMaxSteps = 4;
  90190. }
  90191. _this._options = options;
  90192. // Init caps
  90193. // We consider we are on a webgl1 capable device
  90194. _this._caps = new BABYLON.EngineCapabilities();
  90195. _this._caps.maxTexturesImageUnits = 16;
  90196. _this._caps.maxVertexTextureImageUnits = 16;
  90197. _this._caps.maxTextureSize = 512;
  90198. _this._caps.maxCubemapTextureSize = 512;
  90199. _this._caps.maxRenderTextureSize = 512;
  90200. _this._caps.maxVertexAttribs = 16;
  90201. _this._caps.maxVaryingVectors = 16;
  90202. _this._caps.maxFragmentUniformVectors = 16;
  90203. _this._caps.maxVertexUniformVectors = 16;
  90204. // Extensions
  90205. _this._caps.standardDerivatives = false;
  90206. _this._caps.astc = null;
  90207. _this._caps.s3tc = null;
  90208. _this._caps.pvrtc = null;
  90209. _this._caps.etc1 = null;
  90210. _this._caps.etc2 = null;
  90211. _this._caps.textureAnisotropicFilterExtension = null;
  90212. _this._caps.maxAnisotropy = 0;
  90213. _this._caps.uintIndices = false;
  90214. _this._caps.fragmentDepthSupported = false;
  90215. _this._caps.highPrecisionShaderSupported = true;
  90216. _this._caps.colorBufferFloat = false;
  90217. _this._caps.textureFloat = false;
  90218. _this._caps.textureFloatLinearFiltering = false;
  90219. _this._caps.textureFloatRender = false;
  90220. _this._caps.textureHalfFloat = false;
  90221. _this._caps.textureHalfFloatLinearFiltering = false;
  90222. _this._caps.textureHalfFloatRender = false;
  90223. _this._caps.textureLOD = false;
  90224. _this._caps.drawBuffersExtension = false;
  90225. _this._caps.depthTextureExtension = false;
  90226. _this._caps.vertexArrayObject = false;
  90227. _this._caps.instancedArrays = false;
  90228. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  90229. // Wrappers
  90230. if (typeof URL === "undefined") {
  90231. URL = {
  90232. createObjectURL: function () { },
  90233. revokeObjectURL: function () { }
  90234. };
  90235. }
  90236. if (typeof Blob === "undefined") {
  90237. Blob = function () { };
  90238. }
  90239. return _this;
  90240. }
  90241. NullEngine.prototype.isDeterministicLockStep = function () {
  90242. return this._options.deterministicLockstep;
  90243. };
  90244. NullEngine.prototype.getLockstepMaxSteps = function () {
  90245. return this._options.lockstepMaxSteps;
  90246. };
  90247. NullEngine.prototype.getHardwareScalingLevel = function () {
  90248. return 1.0;
  90249. };
  90250. NullEngine.prototype.createVertexBuffer = function (vertices) {
  90251. return {
  90252. capacity: 0,
  90253. references: 1,
  90254. is32Bits: false
  90255. };
  90256. };
  90257. NullEngine.prototype.createIndexBuffer = function (indices) {
  90258. return {
  90259. capacity: 0,
  90260. references: 1,
  90261. is32Bits: false
  90262. };
  90263. };
  90264. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  90265. if (stencil === void 0) { stencil = false; }
  90266. };
  90267. NullEngine.prototype.getRenderWidth = function (useScreen) {
  90268. if (useScreen === void 0) { useScreen = false; }
  90269. if (!useScreen && this._currentRenderTarget) {
  90270. return this._currentRenderTarget.width;
  90271. }
  90272. return this._options.renderWidth;
  90273. };
  90274. NullEngine.prototype.getRenderHeight = function (useScreen) {
  90275. if (useScreen === void 0) { useScreen = false; }
  90276. if (!useScreen && this._currentRenderTarget) {
  90277. return this._currentRenderTarget.height;
  90278. }
  90279. return this._options.renderHeight;
  90280. };
  90281. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  90282. this._cachedViewport = viewport;
  90283. };
  90284. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  90285. return {
  90286. transformFeedback: null,
  90287. __SPECTOR_rebuildProgram: null
  90288. };
  90289. };
  90290. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  90291. return [];
  90292. };
  90293. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  90294. return [];
  90295. };
  90296. NullEngine.prototype.bindSamplers = function (effect) {
  90297. this._currentEffect = null;
  90298. };
  90299. NullEngine.prototype.enableEffect = function (effect) {
  90300. this._currentEffect = effect;
  90301. if (effect.onBind) {
  90302. effect.onBind(effect);
  90303. }
  90304. effect.onBindObservable.notifyObservers(effect);
  90305. };
  90306. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  90307. if (zOffset === void 0) { zOffset = 0; }
  90308. if (reverseSide === void 0) { reverseSide = false; }
  90309. };
  90310. NullEngine.prototype.setIntArray = function (uniform, array) {
  90311. };
  90312. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  90313. };
  90314. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  90315. };
  90316. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  90317. };
  90318. NullEngine.prototype.setFloatArray = function (uniform, array) {
  90319. };
  90320. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  90321. };
  90322. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  90323. };
  90324. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  90325. };
  90326. NullEngine.prototype.setArray = function (uniform, array) {
  90327. };
  90328. NullEngine.prototype.setArray2 = function (uniform, array) {
  90329. };
  90330. NullEngine.prototype.setArray3 = function (uniform, array) {
  90331. };
  90332. NullEngine.prototype.setArray4 = function (uniform, array) {
  90333. };
  90334. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  90335. };
  90336. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  90337. };
  90338. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  90339. };
  90340. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  90341. };
  90342. NullEngine.prototype.setFloat = function (uniform, value) {
  90343. };
  90344. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  90345. };
  90346. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  90347. };
  90348. NullEngine.prototype.setBool = function (uniform, bool) {
  90349. };
  90350. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  90351. };
  90352. NullEngine.prototype.setColor3 = function (uniform, color3) {
  90353. };
  90354. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  90355. };
  90356. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  90357. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  90358. if (this._alphaMode === mode) {
  90359. return;
  90360. }
  90361. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  90362. if (!noDepthWriteChange) {
  90363. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  90364. }
  90365. this._alphaMode = mode;
  90366. };
  90367. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  90368. };
  90369. NullEngine.prototype.wipeCaches = function (bruteForce) {
  90370. if (this.preventCacheWipeBetweenFrames) {
  90371. return;
  90372. }
  90373. this.resetTextureCache();
  90374. this._currentEffect = null;
  90375. if (bruteForce) {
  90376. this._currentProgram = null;
  90377. this._stencilState.reset();
  90378. this._depthCullingState.reset();
  90379. this._alphaState.reset();
  90380. }
  90381. this._cachedVertexBuffers = null;
  90382. this._cachedIndexBuffer = null;
  90383. this._cachedEffectForVertexBuffers = null;
  90384. };
  90385. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  90386. };
  90387. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  90388. };
  90389. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  90390. };
  90391. NullEngine.prototype._createTexture = function () {
  90392. return {};
  90393. };
  90394. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  90395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  90396. if (onLoad === void 0) { onLoad = null; }
  90397. if (onError === void 0) { onError = null; }
  90398. if (buffer === void 0) { buffer = null; }
  90399. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  90400. var url = String(urlArg);
  90401. texture.url = url;
  90402. texture.generateMipMaps = !noMipmap;
  90403. texture.samplingMode = samplingMode;
  90404. texture.invertY = invertY;
  90405. texture.baseWidth = this._options.textureSize;
  90406. texture.baseHeight = this._options.textureSize;
  90407. texture.width = this._options.textureSize;
  90408. texture.height = this._options.textureSize;
  90409. if (format) {
  90410. texture.format = format;
  90411. }
  90412. texture.isReady = true;
  90413. if (onLoad) {
  90414. onLoad();
  90415. }
  90416. return texture;
  90417. };
  90418. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  90419. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  90420. if (options !== undefined && typeof options === "object") {
  90421. fullOptions.generateMipMaps = options.generateMipMaps;
  90422. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  90423. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  90424. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  90425. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  90426. }
  90427. else {
  90428. fullOptions.generateMipMaps = options;
  90429. fullOptions.generateDepthBuffer = true;
  90430. fullOptions.generateStencilBuffer = false;
  90431. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90432. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90433. }
  90434. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  90435. var width = size.width || size;
  90436. var height = size.height || size;
  90437. texture._depthStencilBuffer = {};
  90438. texture._framebuffer = {};
  90439. texture.baseWidth = width;
  90440. texture.baseHeight = height;
  90441. texture.width = width;
  90442. texture.height = height;
  90443. texture.isReady = true;
  90444. texture.samples = 1;
  90445. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  90446. texture.samplingMode = fullOptions.samplingMode;
  90447. texture.type = fullOptions.type;
  90448. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  90449. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  90450. return texture;
  90451. };
  90452. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  90453. texture.samplingMode = samplingMode;
  90454. };
  90455. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  90456. if (this._currentRenderTarget) {
  90457. this.unBindFramebuffer(this._currentRenderTarget);
  90458. }
  90459. this._currentRenderTarget = texture;
  90460. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  90461. if (this._cachedViewport && !forceFullscreenViewport) {
  90462. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  90463. }
  90464. };
  90465. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  90466. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  90467. this._currentRenderTarget = null;
  90468. if (onBeforeUnbind) {
  90469. if (texture._MSAAFramebuffer) {
  90470. this._currentFramebuffer = texture._framebuffer;
  90471. }
  90472. onBeforeUnbind();
  90473. }
  90474. this._currentFramebuffer = null;
  90475. };
  90476. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  90477. var vbo = {
  90478. capacity: 1,
  90479. references: 1,
  90480. is32Bits: false
  90481. };
  90482. return vbo;
  90483. };
  90484. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  90485. if (offset === void 0) { offset = 0; }
  90486. };
  90487. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  90488. };
  90489. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  90490. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  90491. this._boundTexturesCache[this._activeChannel] = texture;
  90492. }
  90493. };
  90494. NullEngine.prototype._bindTexture = function (channel, texture) {
  90495. if (channel < 0) {
  90496. return;
  90497. }
  90498. this._bindTextureDirectly(0, texture);
  90499. };
  90500. NullEngine.prototype._releaseBuffer = function (buffer) {
  90501. buffer.references--;
  90502. if (buffer.references === 0) {
  90503. return true;
  90504. }
  90505. return false;
  90506. };
  90507. return NullEngine;
  90508. }(BABYLON.Engine));
  90509. BABYLON.NullEngine = NullEngine;
  90510. })(BABYLON || (BABYLON = {}));
  90511. //# sourceMappingURL=babylon.nullEngine.js.map
  90512. "use strict";
  90513. var BABYLON;
  90514. (function (BABYLON) {
  90515. /**
  90516. * This class can be used to get instrumentation data from a Babylon engine
  90517. */
  90518. var EngineInstrumentation = /** @class */ (function () {
  90519. function EngineInstrumentation(engine) {
  90520. this.engine = engine;
  90521. this._captureGPUFrameTime = false;
  90522. this._gpuFrameTime = new BABYLON.PerfCounter();
  90523. this._captureShaderCompilationTime = false;
  90524. this._shaderCompilationTime = new BABYLON.PerfCounter();
  90525. // Observers
  90526. this._onBeginFrameObserver = null;
  90527. this._onEndFrameObserver = null;
  90528. this._onBeforeShaderCompilationObserver = null;
  90529. this._onAfterShaderCompilationObserver = null;
  90530. }
  90531. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  90532. // Properties
  90533. /**
  90534. * Gets the perf counter used for GPU frame time
  90535. */
  90536. get: function () {
  90537. return this._gpuFrameTime;
  90538. },
  90539. enumerable: true,
  90540. configurable: true
  90541. });
  90542. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  90543. /**
  90544. * Gets the GPU frame time capture status
  90545. */
  90546. get: function () {
  90547. return this._captureGPUFrameTime;
  90548. },
  90549. /**
  90550. * Enable or disable the GPU frame time capture
  90551. */
  90552. set: function (value) {
  90553. var _this = this;
  90554. if (value === this._captureGPUFrameTime) {
  90555. return;
  90556. }
  90557. this._captureGPUFrameTime = value;
  90558. if (value) {
  90559. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90560. if (!_this._gpuFrameTimeToken) {
  90561. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90562. }
  90563. });
  90564. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90565. if (!_this._gpuFrameTimeToken) {
  90566. return;
  90567. }
  90568. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90569. if (time > -1) {
  90570. _this._gpuFrameTimeToken = null;
  90571. _this._gpuFrameTime.fetchNewFrame();
  90572. _this._gpuFrameTime.addCount(time, true);
  90573. }
  90574. });
  90575. }
  90576. else {
  90577. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90578. this._onBeginFrameObserver = null;
  90579. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90580. this._onEndFrameObserver = null;
  90581. }
  90582. },
  90583. enumerable: true,
  90584. configurable: true
  90585. });
  90586. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90587. /**
  90588. * Gets the perf counter used for shader compilation time
  90589. */
  90590. get: function () {
  90591. return this._shaderCompilationTime;
  90592. },
  90593. enumerable: true,
  90594. configurable: true
  90595. });
  90596. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90597. /**
  90598. * Gets the shader compilation time capture status
  90599. */
  90600. get: function () {
  90601. return this._captureShaderCompilationTime;
  90602. },
  90603. /**
  90604. * Enable or disable the shader compilation time capture
  90605. */
  90606. set: function (value) {
  90607. var _this = this;
  90608. if (value === this._captureShaderCompilationTime) {
  90609. return;
  90610. }
  90611. this._captureShaderCompilationTime = value;
  90612. if (value) {
  90613. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90614. _this._shaderCompilationTime.fetchNewFrame();
  90615. _this._shaderCompilationTime.beginMonitoring();
  90616. });
  90617. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90618. _this._shaderCompilationTime.endMonitoring();
  90619. });
  90620. }
  90621. else {
  90622. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90623. this._onBeforeShaderCompilationObserver = null;
  90624. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90625. this._onAfterShaderCompilationObserver = null;
  90626. }
  90627. },
  90628. enumerable: true,
  90629. configurable: true
  90630. });
  90631. EngineInstrumentation.prototype.dispose = function () {
  90632. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90633. this._onBeginFrameObserver = null;
  90634. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90635. this._onEndFrameObserver = null;
  90636. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90637. this._onBeforeShaderCompilationObserver = null;
  90638. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90639. this._onAfterShaderCompilationObserver = null;
  90640. this.engine = null;
  90641. };
  90642. return EngineInstrumentation;
  90643. }());
  90644. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90645. })(BABYLON || (BABYLON = {}));
  90646. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90647. "use strict";
  90648. var BABYLON;
  90649. (function (BABYLON) {
  90650. /**
  90651. * This class can be used to get instrumentation data from a Babylon engine
  90652. */
  90653. var SceneInstrumentation = /** @class */ (function () {
  90654. function SceneInstrumentation(scene) {
  90655. var _this = this;
  90656. this.scene = scene;
  90657. this._captureActiveMeshesEvaluationTime = false;
  90658. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90659. this._captureRenderTargetsRenderTime = false;
  90660. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90661. this._captureFrameTime = false;
  90662. this._frameTime = new BABYLON.PerfCounter();
  90663. this._captureRenderTime = false;
  90664. this._renderTime = new BABYLON.PerfCounter();
  90665. this._captureInterFrameTime = false;
  90666. this._interFrameTime = new BABYLON.PerfCounter();
  90667. this._captureParticlesRenderTime = false;
  90668. this._particlesRenderTime = new BABYLON.PerfCounter();
  90669. this._captureSpritesRenderTime = false;
  90670. this._spritesRenderTime = new BABYLON.PerfCounter();
  90671. this._capturePhysicsTime = false;
  90672. this._physicsTime = new BABYLON.PerfCounter();
  90673. this._captureAnimationsTime = false;
  90674. this._animationsTime = new BABYLON.PerfCounter();
  90675. // Observers
  90676. this._onBeforeActiveMeshesEvaluationObserver = null;
  90677. this._onAfterActiveMeshesEvaluationObserver = null;
  90678. this._onBeforeRenderTargetsRenderObserver = null;
  90679. this._onAfterRenderTargetsRenderObserver = null;
  90680. this._onAfterRenderObserver = null;
  90681. this._onBeforeDrawPhaseObserver = null;
  90682. this._onAfterDrawPhaseObserver = null;
  90683. this._onBeforeAnimationsObserver = null;
  90684. this._onBeforeParticlesRenderingObserver = null;
  90685. this._onAfterParticlesRenderingObserver = null;
  90686. this._onBeforeSpritesRenderingObserver = null;
  90687. this._onAfterSpritesRenderingObserver = null;
  90688. this._onBeforePhysicsObserver = null;
  90689. this._onAfterPhysicsObserver = null;
  90690. this._onAfterAnimationsObserver = null;
  90691. // Before render
  90692. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90693. if (_this._captureActiveMeshesEvaluationTime) {
  90694. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90695. }
  90696. if (_this._captureRenderTargetsRenderTime) {
  90697. _this._renderTargetsRenderTime.fetchNewFrame();
  90698. }
  90699. if (_this._captureFrameTime) {
  90700. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90701. _this._frameTime.beginMonitoring();
  90702. }
  90703. if (_this._captureInterFrameTime) {
  90704. _this._interFrameTime.endMonitoring();
  90705. }
  90706. if (_this._captureParticlesRenderTime) {
  90707. _this._particlesRenderTime.fetchNewFrame();
  90708. }
  90709. if (_this._captureSpritesRenderTime) {
  90710. _this._spritesRenderTime.fetchNewFrame();
  90711. }
  90712. if (_this._captureAnimationsTime) {
  90713. _this._animationsTime.beginMonitoring();
  90714. }
  90715. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90716. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90717. });
  90718. // After render
  90719. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90720. if (_this._captureFrameTime) {
  90721. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90722. _this._frameTime.endMonitoring();
  90723. }
  90724. if (_this._captureRenderTime) {
  90725. _this._renderTime.endMonitoring(false);
  90726. }
  90727. if (_this._captureInterFrameTime) {
  90728. _this._interFrameTime.beginMonitoring();
  90729. }
  90730. });
  90731. }
  90732. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90733. // Properties
  90734. /**
  90735. * Gets the perf counter used for active meshes evaluation time
  90736. */
  90737. get: function () {
  90738. return this._activeMeshesEvaluationTime;
  90739. },
  90740. enumerable: true,
  90741. configurable: true
  90742. });
  90743. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90744. /**
  90745. * Gets the active meshes evaluation time capture status
  90746. */
  90747. get: function () {
  90748. return this._captureActiveMeshesEvaluationTime;
  90749. },
  90750. /**
  90751. * Enable or disable the active meshes evaluation time capture
  90752. */
  90753. set: function (value) {
  90754. var _this = this;
  90755. if (value === this._captureActiveMeshesEvaluationTime) {
  90756. return;
  90757. }
  90758. this._captureActiveMeshesEvaluationTime = value;
  90759. if (value) {
  90760. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90761. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90762. _this._activeMeshesEvaluationTime.beginMonitoring();
  90763. });
  90764. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90765. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90766. _this._activeMeshesEvaluationTime.endMonitoring();
  90767. });
  90768. }
  90769. else {
  90770. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90771. this._onBeforeActiveMeshesEvaluationObserver = null;
  90772. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90773. this._onAfterActiveMeshesEvaluationObserver = null;
  90774. }
  90775. },
  90776. enumerable: true,
  90777. configurable: true
  90778. });
  90779. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90780. /**
  90781. * Gets the perf counter used for render targets render time
  90782. */
  90783. get: function () {
  90784. return this._renderTargetsRenderTime;
  90785. },
  90786. enumerable: true,
  90787. configurable: true
  90788. });
  90789. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90790. /**
  90791. * Gets the render targets render time capture status
  90792. */
  90793. get: function () {
  90794. return this._captureRenderTargetsRenderTime;
  90795. },
  90796. /**
  90797. * Enable or disable the render targets render time capture
  90798. */
  90799. set: function (value) {
  90800. var _this = this;
  90801. if (value === this._captureRenderTargetsRenderTime) {
  90802. return;
  90803. }
  90804. this._captureRenderTargetsRenderTime = value;
  90805. if (value) {
  90806. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90807. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90808. _this._renderTargetsRenderTime.beginMonitoring();
  90809. });
  90810. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90811. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90812. _this._renderTargetsRenderTime.endMonitoring(false);
  90813. });
  90814. }
  90815. else {
  90816. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90817. this._onBeforeRenderTargetsRenderObserver = null;
  90818. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90819. this._onAfterRenderTargetsRenderObserver = null;
  90820. }
  90821. },
  90822. enumerable: true,
  90823. configurable: true
  90824. });
  90825. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90826. /**
  90827. * Gets the perf counter used for particles render time
  90828. */
  90829. get: function () {
  90830. return this._particlesRenderTime;
  90831. },
  90832. enumerable: true,
  90833. configurable: true
  90834. });
  90835. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90836. /**
  90837. * Gets the particles render time capture status
  90838. */
  90839. get: function () {
  90840. return this._captureParticlesRenderTime;
  90841. },
  90842. /**
  90843. * Enable or disable the particles render time capture
  90844. */
  90845. set: function (value) {
  90846. var _this = this;
  90847. if (value === this._captureParticlesRenderTime) {
  90848. return;
  90849. }
  90850. this._captureParticlesRenderTime = value;
  90851. if (value) {
  90852. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90853. BABYLON.Tools.StartPerformanceCounter("Particles");
  90854. _this._particlesRenderTime.beginMonitoring();
  90855. });
  90856. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90857. BABYLON.Tools.EndPerformanceCounter("Particles");
  90858. _this._particlesRenderTime.endMonitoring(false);
  90859. });
  90860. }
  90861. else {
  90862. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90863. this._onBeforeParticlesRenderingObserver = null;
  90864. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90865. this._onAfterParticlesRenderingObserver = null;
  90866. }
  90867. },
  90868. enumerable: true,
  90869. configurable: true
  90870. });
  90871. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90872. /**
  90873. * Gets the perf counter used for sprites render time
  90874. */
  90875. get: function () {
  90876. return this._spritesRenderTime;
  90877. },
  90878. enumerable: true,
  90879. configurable: true
  90880. });
  90881. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90882. /**
  90883. * Gets the sprites render time capture status
  90884. */
  90885. get: function () {
  90886. return this._captureSpritesRenderTime;
  90887. },
  90888. /**
  90889. * Enable or disable the sprites render time capture
  90890. */
  90891. set: function (value) {
  90892. var _this = this;
  90893. if (value === this._captureSpritesRenderTime) {
  90894. return;
  90895. }
  90896. this._captureSpritesRenderTime = value;
  90897. if (value) {
  90898. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90899. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90900. _this._spritesRenderTime.beginMonitoring();
  90901. });
  90902. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90903. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90904. _this._spritesRenderTime.endMonitoring(false);
  90905. });
  90906. }
  90907. else {
  90908. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90909. this._onBeforeSpritesRenderingObserver = null;
  90910. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90911. this._onAfterSpritesRenderingObserver = null;
  90912. }
  90913. },
  90914. enumerable: true,
  90915. configurable: true
  90916. });
  90917. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90918. /**
  90919. * Gets the perf counter used for physics time
  90920. */
  90921. get: function () {
  90922. return this._physicsTime;
  90923. },
  90924. enumerable: true,
  90925. configurable: true
  90926. });
  90927. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90928. /**
  90929. * Gets the physics time capture status
  90930. */
  90931. get: function () {
  90932. return this._capturePhysicsTime;
  90933. },
  90934. /**
  90935. * Enable or disable the physics time capture
  90936. */
  90937. set: function (value) {
  90938. var _this = this;
  90939. if (value === this._capturePhysicsTime) {
  90940. return;
  90941. }
  90942. this._capturePhysicsTime = value;
  90943. if (value) {
  90944. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90945. BABYLON.Tools.StartPerformanceCounter("Physics");
  90946. _this._physicsTime.beginMonitoring();
  90947. });
  90948. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90949. BABYLON.Tools.EndPerformanceCounter("Physics");
  90950. _this._physicsTime.endMonitoring();
  90951. });
  90952. }
  90953. else {
  90954. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90955. this._onBeforePhysicsObserver = null;
  90956. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90957. this._onAfterPhysicsObserver = null;
  90958. }
  90959. },
  90960. enumerable: true,
  90961. configurable: true
  90962. });
  90963. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90964. /**
  90965. * Gets the perf counter used for animations time
  90966. */
  90967. get: function () {
  90968. return this._animationsTime;
  90969. },
  90970. enumerable: true,
  90971. configurable: true
  90972. });
  90973. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90974. /**
  90975. * Gets the animations time capture status
  90976. */
  90977. get: function () {
  90978. return this._captureAnimationsTime;
  90979. },
  90980. /**
  90981. * Enable or disable the animations time capture
  90982. */
  90983. set: function (value) {
  90984. var _this = this;
  90985. if (value === this._captureAnimationsTime) {
  90986. return;
  90987. }
  90988. this._captureAnimationsTime = value;
  90989. if (value) {
  90990. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90991. _this._animationsTime.endMonitoring();
  90992. });
  90993. }
  90994. else {
  90995. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90996. this._onAfterAnimationsObserver = null;
  90997. }
  90998. },
  90999. enumerable: true,
  91000. configurable: true
  91001. });
  91002. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  91003. /**
  91004. * Gets the perf counter used for frame time capture
  91005. */
  91006. get: function () {
  91007. return this._frameTime;
  91008. },
  91009. enumerable: true,
  91010. configurable: true
  91011. });
  91012. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  91013. /**
  91014. * Gets the frame time capture status
  91015. */
  91016. get: function () {
  91017. return this._captureFrameTime;
  91018. },
  91019. /**
  91020. * Enable or disable the frame time capture
  91021. */
  91022. set: function (value) {
  91023. this._captureFrameTime = value;
  91024. },
  91025. enumerable: true,
  91026. configurable: true
  91027. });
  91028. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  91029. /**
  91030. * Gets the perf counter used for inter-frames time capture
  91031. */
  91032. get: function () {
  91033. return this._interFrameTime;
  91034. },
  91035. enumerable: true,
  91036. configurable: true
  91037. });
  91038. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  91039. /**
  91040. * Gets the inter-frames time capture status
  91041. */
  91042. get: function () {
  91043. return this._captureInterFrameTime;
  91044. },
  91045. /**
  91046. * Enable or disable the inter-frames time capture
  91047. */
  91048. set: function (value) {
  91049. this._captureInterFrameTime = value;
  91050. },
  91051. enumerable: true,
  91052. configurable: true
  91053. });
  91054. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  91055. /**
  91056. * Gets the perf counter used for render time capture
  91057. */
  91058. get: function () {
  91059. return this._renderTime;
  91060. },
  91061. enumerable: true,
  91062. configurable: true
  91063. });
  91064. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  91065. /**
  91066. * Gets the render time capture status
  91067. */
  91068. get: function () {
  91069. return this._captureRenderTime;
  91070. },
  91071. /**
  91072. * Enable or disable the render time capture
  91073. */
  91074. set: function (value) {
  91075. var _this = this;
  91076. if (value === this._captureRenderTime) {
  91077. return;
  91078. }
  91079. this._captureRenderTime = value;
  91080. if (value) {
  91081. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  91082. _this._renderTime.beginMonitoring();
  91083. BABYLON.Tools.StartPerformanceCounter("Main render");
  91084. });
  91085. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  91086. _this._renderTime.endMonitoring(false);
  91087. BABYLON.Tools.EndPerformanceCounter("Main render");
  91088. });
  91089. }
  91090. else {
  91091. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91092. this._onBeforeDrawPhaseObserver = null;
  91093. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91094. this._onAfterDrawPhaseObserver = null;
  91095. }
  91096. },
  91097. enumerable: true,
  91098. configurable: true
  91099. });
  91100. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  91101. /**
  91102. * Gets the perf counter used for draw calls
  91103. */
  91104. get: function () {
  91105. return this.scene.getEngine()._drawCalls;
  91106. },
  91107. enumerable: true,
  91108. configurable: true
  91109. });
  91110. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  91111. /**
  91112. * Gets the perf counter used for texture collisions
  91113. */
  91114. get: function () {
  91115. return this.scene.getEngine()._textureCollisions;
  91116. },
  91117. enumerable: true,
  91118. configurable: true
  91119. });
  91120. SceneInstrumentation.prototype.dispose = function () {
  91121. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  91122. this._onAfterRenderObserver = null;
  91123. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  91124. this._onBeforeActiveMeshesEvaluationObserver = null;
  91125. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  91126. this._onAfterActiveMeshesEvaluationObserver = null;
  91127. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  91128. this._onBeforeRenderTargetsRenderObserver = null;
  91129. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  91130. this._onAfterRenderTargetsRenderObserver = null;
  91131. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  91132. this._onBeforeAnimationsObserver = null;
  91133. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  91134. this._onBeforeParticlesRenderingObserver = null;
  91135. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  91136. this._onAfterParticlesRenderingObserver = null;
  91137. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  91138. this._onBeforeSpritesRenderingObserver = null;
  91139. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  91140. this._onAfterSpritesRenderingObserver = null;
  91141. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  91142. this._onBeforeDrawPhaseObserver = null;
  91143. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  91144. this._onAfterDrawPhaseObserver = null;
  91145. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  91146. this._onBeforePhysicsObserver = null;
  91147. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  91148. this._onAfterPhysicsObserver = null;
  91149. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  91150. this._onAfterAnimationsObserver = null;
  91151. this.scene = null;
  91152. };
  91153. return SceneInstrumentation;
  91154. }());
  91155. BABYLON.SceneInstrumentation = SceneInstrumentation;
  91156. })(BABYLON || (BABYLON = {}));
  91157. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  91158. "use strict";
  91159. var BABYLON;
  91160. (function (BABYLON) {
  91161. var _TimeToken = /** @class */ (function () {
  91162. function _TimeToken() {
  91163. this._timeElapsedQueryEnded = false;
  91164. }
  91165. return _TimeToken;
  91166. }());
  91167. BABYLON._TimeToken = _TimeToken;
  91168. })(BABYLON || (BABYLON = {}));
  91169. //# sourceMappingURL=babylon.timeToken.js.map
  91170. "use strict";
  91171. var BABYLON;
  91172. (function (BABYLON) {
  91173. /**
  91174. * Background material defines definition.
  91175. * @ignore Mainly internal Use
  91176. */
  91177. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  91178. __extends(BackgroundMaterialDefines, _super);
  91179. /**
  91180. * Constructor of the defines.
  91181. */
  91182. function BackgroundMaterialDefines() {
  91183. var _this = _super.call(this) || this;
  91184. /**
  91185. * True if the diffuse texture is in use.
  91186. */
  91187. _this.DIFFUSE = false;
  91188. /**
  91189. * The direct UV channel to use.
  91190. */
  91191. _this.DIFFUSEDIRECTUV = 0;
  91192. /**
  91193. * True if the diffuse texture is in gamma space.
  91194. */
  91195. _this.GAMMADIFFUSE = false;
  91196. /**
  91197. * True if the diffuse texture has opacity in the alpha channel.
  91198. */
  91199. _this.DIFFUSEHASALPHA = false;
  91200. /**
  91201. * True if you want the material to fade to transparent at grazing angle.
  91202. */
  91203. _this.OPACITYFRESNEL = false;
  91204. /**
  91205. * True if an extra blur needs to be added in the reflection.
  91206. */
  91207. _this.REFLECTIONBLUR = false;
  91208. /**
  91209. * True if you want the material to fade to reflection at grazing angle.
  91210. */
  91211. _this.REFLECTIONFRESNEL = false;
  91212. /**
  91213. * True if you want the material to falloff as far as you move away from the scene center.
  91214. */
  91215. _this.REFLECTIONFALLOFF = false;
  91216. /**
  91217. * False if the current Webgl implementation does not support the texture lod extension.
  91218. */
  91219. _this.TEXTURELODSUPPORT = false;
  91220. /**
  91221. * True to ensure the data are premultiplied.
  91222. */
  91223. _this.PREMULTIPLYALPHA = false;
  91224. /**
  91225. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  91226. */
  91227. _this.USERGBCOLOR = false;
  91228. /**
  91229. * True to add noise in order to reduce the banding effect.
  91230. */
  91231. _this.NOISE = false;
  91232. /**
  91233. * is the reflection texture in BGR color scheme?
  91234. * Mainly used to solve a bug in ios10 video tag
  91235. */
  91236. _this.REFLECTIONBGR = false;
  91237. _this.IMAGEPROCESSING = false;
  91238. _this.VIGNETTE = false;
  91239. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  91240. _this.VIGNETTEBLENDMODEOPAQUE = false;
  91241. _this.TONEMAPPING = false;
  91242. _this.CONTRAST = false;
  91243. _this.COLORCURVES = false;
  91244. _this.COLORGRADING = false;
  91245. _this.COLORGRADING3D = false;
  91246. _this.SAMPLER3DGREENDEPTH = false;
  91247. _this.SAMPLER3DBGRMAP = false;
  91248. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  91249. _this.EXPOSURE = false;
  91250. // Reflection.
  91251. _this.REFLECTION = false;
  91252. _this.REFLECTIONMAP_3D = false;
  91253. _this.REFLECTIONMAP_SPHERICAL = false;
  91254. _this.REFLECTIONMAP_PLANAR = false;
  91255. _this.REFLECTIONMAP_CUBIC = false;
  91256. _this.REFLECTIONMAP_PROJECTION = false;
  91257. _this.REFLECTIONMAP_SKYBOX = false;
  91258. _this.REFLECTIONMAP_EXPLICIT = false;
  91259. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91260. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91261. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91262. _this.INVERTCUBICMAP = false;
  91263. _this.REFLECTIONMAP_OPPOSITEZ = false;
  91264. _this.LODINREFLECTIONALPHA = false;
  91265. _this.GAMMAREFLECTION = false;
  91266. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  91267. // Default BJS.
  91268. _this.MAINUV1 = false;
  91269. _this.MAINUV2 = false;
  91270. _this.UV1 = false;
  91271. _this.UV2 = false;
  91272. _this.CLIPPLANE = false;
  91273. _this.POINTSIZE = false;
  91274. _this.FOG = false;
  91275. _this.NORMAL = false;
  91276. _this.NUM_BONE_INFLUENCERS = 0;
  91277. _this.BonesPerMesh = 0;
  91278. _this.INSTANCES = false;
  91279. _this.SHADOWFLOAT = false;
  91280. _this.rebuild();
  91281. return _this;
  91282. }
  91283. return BackgroundMaterialDefines;
  91284. }(BABYLON.MaterialDefines));
  91285. /**
  91286. * Background material used to create an efficient environement around your scene.
  91287. */
  91288. var BackgroundMaterial = /** @class */ (function (_super) {
  91289. __extends(BackgroundMaterial, _super);
  91290. /**
  91291. * Instantiates a Background Material in the given scene
  91292. * @param name The friendly name of the material
  91293. * @param scene The scene to add the material to
  91294. */
  91295. function BackgroundMaterial(name, scene) {
  91296. var _this = _super.call(this, name, scene) || this;
  91297. /**
  91298. * Key light Color (multiply against the R channel of the environement texture)
  91299. */
  91300. _this.primaryColor = BABYLON.Color3.White();
  91301. /**
  91302. * Key light Level (allowing HDR output of the background)
  91303. */
  91304. _this.primaryLevel = 1;
  91305. /**
  91306. * Secondary light Color (multiply against the G channel of the environement texture)
  91307. */
  91308. _this.secondaryColor = BABYLON.Color3.Gray();
  91309. /**
  91310. * Secondary light Level (allowing HDR output of the background)
  91311. */
  91312. _this.secondaryLevel = 1;
  91313. /**
  91314. * Tertiary light Color (multiply against the B channel of the environement texture)
  91315. */
  91316. _this.tertiaryColor = BABYLON.Color3.Black();
  91317. /**
  91318. * Tertiary light Level (allowing HDR output of the background)
  91319. */
  91320. _this.tertiaryLevel = 1;
  91321. /**
  91322. * Reflection Texture used in the material.
  91323. * Should be author in a specific way for the best result (refer to the documentation).
  91324. */
  91325. _this.reflectionTexture = null;
  91326. /**
  91327. * Reflection Texture level of blur.
  91328. *
  91329. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  91330. * texture twice.
  91331. */
  91332. _this.reflectionBlur = 0;
  91333. /**
  91334. * Diffuse Texture used in the material.
  91335. * Should be author in a specific way for the best result (refer to the documentation).
  91336. */
  91337. _this.diffuseTexture = null;
  91338. _this._shadowLights = null;
  91339. /**
  91340. * Specify the list of lights casting shadow on the material.
  91341. * All scene shadow lights will be included if null.
  91342. */
  91343. _this.shadowLights = null;
  91344. /**
  91345. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  91346. * soft lighting on the background.
  91347. */
  91348. _this.shadowBlurScale = 1;
  91349. /**
  91350. * Helps adjusting the shadow to a softer level if required.
  91351. * 0 means black shadows and 1 means no shadows.
  91352. */
  91353. _this.shadowLevel = 0;
  91354. /**
  91355. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  91356. * It is usually zero but might be interesting to modify according to your setup.
  91357. */
  91358. _this.sceneCenter = BABYLON.Vector3.Zero();
  91359. /**
  91360. * This helps specifying that the material is falling off to the sky box at grazing angle.
  91361. * This helps ensuring a nice transition when the camera goes under the ground.
  91362. */
  91363. _this.opacityFresnel = true;
  91364. /**
  91365. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  91366. * This helps adding a mirror texture on the ground.
  91367. */
  91368. _this.reflectionFresnel = false;
  91369. /**
  91370. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  91371. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  91372. */
  91373. _this.reflectionFalloffDistance = 0.0;
  91374. /**
  91375. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  91376. */
  91377. _this.reflectionAmount = 1.0;
  91378. /**
  91379. * This specifies the weight of the reflection at grazing angle.
  91380. */
  91381. _this.reflectionReflectance0 = 0.05;
  91382. /**
  91383. * This specifies the weight of the reflection at a perpendicular point of view.
  91384. */
  91385. _this.reflectionReflectance90 = 0.5;
  91386. /**
  91387. * Helps to directly use the maps channels instead of their level.
  91388. */
  91389. _this.useRGBColor = true;
  91390. /**
  91391. * This helps reducing the banding effect that could occur on the background.
  91392. */
  91393. _this.enableNoise = false;
  91394. _this._fovMultiplier = 1.0;
  91395. /**
  91396. * Enable the FOV adjustment feature controlled by fovMultiplier.
  91397. * @type {boolean}
  91398. */
  91399. _this.useEquirectangularFOV = false;
  91400. _this._maxSimultaneousLights = 4;
  91401. /**
  91402. * Number of Simultaneous lights allowed on the material.
  91403. */
  91404. _this.maxSimultaneousLights = 4;
  91405. /**
  91406. * Keep track of the image processing observer to allow dispose and replace.
  91407. */
  91408. _this._imageProcessingObserver = null;
  91409. /**
  91410. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  91411. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  91412. */
  91413. _this.switchToBGR = false;
  91414. // Temp values kept as cache in the material.
  91415. _this._renderTargets = new BABYLON.SmartArray(16);
  91416. _this._reflectionControls = BABYLON.Vector4.Zero();
  91417. // Setup the default processing configuration to the scene.
  91418. _this._attachImageProcessingConfiguration(null);
  91419. _this.getRenderTargetTextures = function () {
  91420. _this._renderTargets.reset();
  91421. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  91422. _this._renderTargets.push(_this._diffuseTexture);
  91423. }
  91424. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  91425. _this._renderTargets.push(_this._reflectionTexture);
  91426. }
  91427. return _this._renderTargets;
  91428. };
  91429. return _this;
  91430. }
  91431. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  91432. /**
  91433. * Sets the reflection reflectance fresnel values according to the default standard
  91434. * empirically know to work well :-)
  91435. */
  91436. set: function (value) {
  91437. var reflectionWeight = value;
  91438. if (reflectionWeight < 0.5) {
  91439. reflectionWeight = reflectionWeight * 2.0;
  91440. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  91441. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  91442. }
  91443. else {
  91444. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  91445. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  91446. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  91447. }
  91448. },
  91449. enumerable: true,
  91450. configurable: true
  91451. });
  91452. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  91453. /**
  91454. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  91455. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  91456. * Recommended to be keep at 1.0 except for special cases.
  91457. */
  91458. get: function () {
  91459. return this._fovMultiplier;
  91460. },
  91461. set: function (value) {
  91462. if (isNaN(value)) {
  91463. value = 1.0;
  91464. }
  91465. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  91466. },
  91467. enumerable: true,
  91468. configurable: true
  91469. });
  91470. /**
  91471. * Attaches a new image processing configuration to the PBR Material.
  91472. * @param configuration (if null the scene configuration will be use)
  91473. */
  91474. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  91475. var _this = this;
  91476. if (configuration === this._imageProcessingConfiguration) {
  91477. return;
  91478. }
  91479. // Detaches observer.
  91480. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91481. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91482. }
  91483. // Pick the scene configuration if needed.
  91484. if (!configuration) {
  91485. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  91486. }
  91487. else {
  91488. this._imageProcessingConfiguration = configuration;
  91489. }
  91490. // Attaches observer.
  91491. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  91492. _this._markAllSubMeshesAsImageProcessingDirty();
  91493. });
  91494. };
  91495. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  91496. /**
  91497. * Gets the image processing configuration used either in this material.
  91498. */
  91499. get: function () {
  91500. return this._imageProcessingConfiguration;
  91501. },
  91502. /**
  91503. * Sets the Default image processing configuration used either in the this material.
  91504. *
  91505. * If sets to null, the scene one is in use.
  91506. */
  91507. set: function (value) {
  91508. this._attachImageProcessingConfiguration(value);
  91509. // Ensure the effect will be rebuilt.
  91510. this._markAllSubMeshesAsTexturesDirty();
  91511. },
  91512. enumerable: true,
  91513. configurable: true
  91514. });
  91515. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  91516. /**
  91517. * Gets wether the color curves effect is enabled.
  91518. */
  91519. get: function () {
  91520. return this.imageProcessingConfiguration.colorCurvesEnabled;
  91521. },
  91522. /**
  91523. * Sets wether the color curves effect is enabled.
  91524. */
  91525. set: function (value) {
  91526. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  91527. },
  91528. enumerable: true,
  91529. configurable: true
  91530. });
  91531. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  91532. /**
  91533. * Gets wether the color grading effect is enabled.
  91534. */
  91535. get: function () {
  91536. return this.imageProcessingConfiguration.colorGradingEnabled;
  91537. },
  91538. /**
  91539. * Gets wether the color grading effect is enabled.
  91540. */
  91541. set: function (value) {
  91542. this.imageProcessingConfiguration.colorGradingEnabled = value;
  91543. },
  91544. enumerable: true,
  91545. configurable: true
  91546. });
  91547. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  91548. /**
  91549. * Gets wether tonemapping is enabled or not.
  91550. */
  91551. get: function () {
  91552. return this._imageProcessingConfiguration.toneMappingEnabled;
  91553. },
  91554. /**
  91555. * Sets wether tonemapping is enabled or not
  91556. */
  91557. set: function (value) {
  91558. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91559. },
  91560. enumerable: true,
  91561. configurable: true
  91562. });
  91563. ;
  91564. ;
  91565. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91566. /**
  91567. * The camera exposure used on this material.
  91568. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91569. * This corresponds to a photographic exposure.
  91570. */
  91571. get: function () {
  91572. return this._imageProcessingConfiguration.exposure;
  91573. },
  91574. /**
  91575. * The camera exposure used on this material.
  91576. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91577. * This corresponds to a photographic exposure.
  91578. */
  91579. set: function (value) {
  91580. this._imageProcessingConfiguration.exposure = value;
  91581. },
  91582. enumerable: true,
  91583. configurable: true
  91584. });
  91585. ;
  91586. ;
  91587. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91588. /**
  91589. * Gets The camera contrast used on this material.
  91590. */
  91591. get: function () {
  91592. return this._imageProcessingConfiguration.contrast;
  91593. },
  91594. /**
  91595. * Sets The camera contrast used on this material.
  91596. */
  91597. set: function (value) {
  91598. this._imageProcessingConfiguration.contrast = value;
  91599. },
  91600. enumerable: true,
  91601. configurable: true
  91602. });
  91603. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91604. /**
  91605. * Gets the Color Grading 2D Lookup Texture.
  91606. */
  91607. get: function () {
  91608. return this._imageProcessingConfiguration.colorGradingTexture;
  91609. },
  91610. /**
  91611. * Sets the Color Grading 2D Lookup Texture.
  91612. */
  91613. set: function (value) {
  91614. this.imageProcessingConfiguration.colorGradingTexture = value;
  91615. },
  91616. enumerable: true,
  91617. configurable: true
  91618. });
  91619. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91620. /**
  91621. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91622. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91623. * 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;
  91624. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91625. */
  91626. get: function () {
  91627. return this.imageProcessingConfiguration.colorCurves;
  91628. },
  91629. /**
  91630. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91631. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91632. * 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;
  91633. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91634. */
  91635. set: function (value) {
  91636. this.imageProcessingConfiguration.colorCurves = value;
  91637. },
  91638. enumerable: true,
  91639. configurable: true
  91640. });
  91641. /**
  91642. * The entire material has been created in order to prevent overdraw.
  91643. * @returns false
  91644. */
  91645. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91646. return true;
  91647. };
  91648. /**
  91649. * The entire material has been created in order to prevent overdraw.
  91650. * @returns true if blending is enable
  91651. */
  91652. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91653. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91654. };
  91655. /**
  91656. * Checks wether the material is ready to be rendered for a given mesh.
  91657. * @param mesh The mesh to render
  91658. * @param subMesh The submesh to check against
  91659. * @param useInstances Specify wether or not the material is used with instances
  91660. * @returns true if all the dependencies are ready (Textures, Effects...)
  91661. */
  91662. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91663. var _this = this;
  91664. if (useInstances === void 0) { useInstances = false; }
  91665. if (subMesh.effect && this.isFrozen) {
  91666. if (this._wasPreviouslyReady) {
  91667. return true;
  91668. }
  91669. }
  91670. if (!subMesh._materialDefines) {
  91671. subMesh._materialDefines = new BackgroundMaterialDefines();
  91672. }
  91673. var scene = this.getScene();
  91674. var defines = subMesh._materialDefines;
  91675. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91676. if (defines._renderId === scene.getRenderId()) {
  91677. return true;
  91678. }
  91679. }
  91680. var engine = scene.getEngine();
  91681. // Lights
  91682. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91683. defines._needNormals = true;
  91684. // Textures
  91685. if (defines._areTexturesDirty) {
  91686. defines._needUVs = false;
  91687. if (scene.texturesEnabled) {
  91688. if (scene.getEngine().getCaps().textureLOD) {
  91689. defines.TEXTURELODSUPPORT = true;
  91690. }
  91691. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91692. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91693. return false;
  91694. }
  91695. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91696. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91697. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91698. defines.OPACITYFRESNEL = this._opacityFresnel;
  91699. }
  91700. else {
  91701. defines.DIFFUSE = false;
  91702. defines.DIFFUSEHASALPHA = false;
  91703. defines.GAMMADIFFUSE = false;
  91704. defines.OPACITYFRESNEL = false;
  91705. }
  91706. var reflectionTexture = this._reflectionTexture;
  91707. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91708. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91709. return false;
  91710. }
  91711. defines.REFLECTION = true;
  91712. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91713. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91714. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91715. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91716. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91717. defines.REFLECTIONBGR = this.switchToBGR;
  91718. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91719. defines.INVERTCUBICMAP = true;
  91720. }
  91721. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91722. switch (reflectionTexture.coordinatesMode) {
  91723. case BABYLON.Texture.CUBIC_MODE:
  91724. case BABYLON.Texture.INVCUBIC_MODE:
  91725. defines.REFLECTIONMAP_CUBIC = true;
  91726. break;
  91727. case BABYLON.Texture.EXPLICIT_MODE:
  91728. defines.REFLECTIONMAP_EXPLICIT = true;
  91729. break;
  91730. case BABYLON.Texture.PLANAR_MODE:
  91731. defines.REFLECTIONMAP_PLANAR = true;
  91732. break;
  91733. case BABYLON.Texture.PROJECTION_MODE:
  91734. defines.REFLECTIONMAP_PROJECTION = true;
  91735. break;
  91736. case BABYLON.Texture.SKYBOX_MODE:
  91737. defines.REFLECTIONMAP_SKYBOX = true;
  91738. break;
  91739. case BABYLON.Texture.SPHERICAL_MODE:
  91740. defines.REFLECTIONMAP_SPHERICAL = true;
  91741. break;
  91742. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91743. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91744. break;
  91745. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91746. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91747. break;
  91748. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91749. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91750. break;
  91751. }
  91752. if (this.reflectionFresnel) {
  91753. defines.REFLECTIONFRESNEL = true;
  91754. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91755. this._reflectionControls.x = this.reflectionAmount;
  91756. this._reflectionControls.y = this.reflectionReflectance0;
  91757. this._reflectionControls.z = this.reflectionReflectance90;
  91758. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91759. }
  91760. else {
  91761. defines.REFLECTIONFRESNEL = false;
  91762. defines.REFLECTIONFALLOFF = false;
  91763. }
  91764. }
  91765. else {
  91766. defines.REFLECTION = false;
  91767. defines.REFLECTIONFALLOFF = false;
  91768. defines.REFLECTIONBLUR = false;
  91769. defines.REFLECTIONMAP_3D = false;
  91770. defines.REFLECTIONMAP_SPHERICAL = false;
  91771. defines.REFLECTIONMAP_PLANAR = false;
  91772. defines.REFLECTIONMAP_CUBIC = false;
  91773. defines.REFLECTIONMAP_PROJECTION = false;
  91774. defines.REFLECTIONMAP_SKYBOX = false;
  91775. defines.REFLECTIONMAP_EXPLICIT = false;
  91776. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91777. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91778. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91779. defines.INVERTCUBICMAP = false;
  91780. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91781. defines.LODINREFLECTIONALPHA = false;
  91782. defines.GAMMAREFLECTION = false;
  91783. }
  91784. }
  91785. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91786. defines.USERGBCOLOR = this._useRGBColor;
  91787. defines.NOISE = this._enableNoise;
  91788. }
  91789. if (defines._areImageProcessingDirty) {
  91790. if (!this._imageProcessingConfiguration.isReady()) {
  91791. return false;
  91792. }
  91793. this._imageProcessingConfiguration.prepareDefines(defines);
  91794. }
  91795. // Misc.
  91796. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91797. // Values that need to be evaluated on every frame
  91798. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91799. // Attribs
  91800. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91801. if (mesh) {
  91802. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91803. mesh.createNormals(true);
  91804. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91805. }
  91806. }
  91807. }
  91808. // Get correct effect
  91809. if (defines.isDirty) {
  91810. defines.markAsProcessed();
  91811. scene.resetCachedMaterial();
  91812. // Fallbacks
  91813. var fallbacks = new BABYLON.EffectFallbacks();
  91814. if (defines.FOG) {
  91815. fallbacks.addFallback(0, "FOG");
  91816. }
  91817. if (defines.POINTSIZE) {
  91818. fallbacks.addFallback(1, "POINTSIZE");
  91819. }
  91820. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91821. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91822. fallbacks.addCPUSkinningFallback(0, mesh);
  91823. }
  91824. //Attributes
  91825. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91826. if (defines.NORMAL) {
  91827. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91828. }
  91829. if (defines.UV1) {
  91830. attribs.push(BABYLON.VertexBuffer.UVKind);
  91831. }
  91832. if (defines.UV2) {
  91833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91834. }
  91835. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91836. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91837. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91838. "vFogInfos", "vFogColor", "pointSize",
  91839. "vClipPlane", "mBones",
  91840. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91841. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91842. "shadowLevel", "alpha",
  91843. "vBackgroundCenter", "vReflectionControl",
  91844. "vDiffuseInfos", "diffuseMatrix",
  91845. ];
  91846. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91847. var uniformBuffers = ["Material", "Scene"];
  91848. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91849. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91850. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91851. uniformsNames: uniforms,
  91852. uniformBuffersNames: uniformBuffers,
  91853. samplers: samplers,
  91854. defines: defines,
  91855. maxSimultaneousLights: this._maxSimultaneousLights
  91856. });
  91857. var onCompiled = function (effect) {
  91858. if (_this.onCompiled) {
  91859. _this.onCompiled(effect);
  91860. }
  91861. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91862. };
  91863. var join = defines.toString();
  91864. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91865. attributes: attribs,
  91866. uniformsNames: uniforms,
  91867. uniformBuffersNames: uniformBuffers,
  91868. samplers: samplers,
  91869. defines: join,
  91870. fallbacks: fallbacks,
  91871. onCompiled: onCompiled,
  91872. onError: this.onError,
  91873. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91874. }, engine), defines);
  91875. this.buildUniformLayout();
  91876. }
  91877. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91878. return false;
  91879. }
  91880. defines._renderId = scene.getRenderId();
  91881. this._wasPreviouslyReady = true;
  91882. return true;
  91883. };
  91884. /**
  91885. * Build the uniform buffer used in the material.
  91886. */
  91887. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91888. // Order is important !
  91889. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91890. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91891. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91892. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91893. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91894. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91895. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91896. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91897. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91898. this._uniformBuffer.addUniform("pointSize", 1);
  91899. this._uniformBuffer.addUniform("shadowLevel", 1);
  91900. this._uniformBuffer.addUniform("alpha", 1);
  91901. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91902. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91903. this._uniformBuffer.create();
  91904. };
  91905. /**
  91906. * Unbind the material.
  91907. */
  91908. BackgroundMaterial.prototype.unbind = function () {
  91909. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91910. this._uniformBuffer.setTexture("diffuseSampler", null);
  91911. }
  91912. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91913. this._uniformBuffer.setTexture("reflectionSampler", null);
  91914. }
  91915. _super.prototype.unbind.call(this);
  91916. };
  91917. /**
  91918. * Bind only the world matrix to the material.
  91919. * @param world The world matrix to bind.
  91920. */
  91921. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91922. this._activeEffect.setMatrix("world", world);
  91923. };
  91924. /**
  91925. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91926. * @param world The world matrix to bind.
  91927. * @param subMesh The submesh to bind for.
  91928. */
  91929. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91930. var scene = this.getScene();
  91931. var defines = subMesh._materialDefines;
  91932. if (!defines) {
  91933. return;
  91934. }
  91935. var effect = subMesh.effect;
  91936. if (!effect) {
  91937. return;
  91938. }
  91939. this._activeEffect = effect;
  91940. // Matrices
  91941. this.bindOnlyWorldMatrix(world);
  91942. // Bones
  91943. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91944. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91945. if (mustRebind) {
  91946. this._uniformBuffer.bindToEffect(effect, "Material");
  91947. this.bindViewProjection(effect);
  91948. var reflectionTexture = this._reflectionTexture;
  91949. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91950. // Texture uniforms
  91951. if (scene.texturesEnabled) {
  91952. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91953. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91954. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91955. }
  91956. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91957. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91958. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91959. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91960. }
  91961. }
  91962. if (this.shadowLevel > 0) {
  91963. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91964. }
  91965. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91966. // Point size
  91967. if (this.pointsCloud) {
  91968. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91969. }
  91970. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91971. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91972. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91973. }
  91974. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91975. // Textures
  91976. if (scene.texturesEnabled) {
  91977. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91978. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91979. }
  91980. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91981. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91982. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91983. }
  91984. else if (!defines.REFLECTIONBLUR) {
  91985. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91986. }
  91987. else {
  91988. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91989. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91990. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91991. }
  91992. if (defines.REFLECTIONFRESNEL) {
  91993. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91994. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91995. }
  91996. }
  91997. }
  91998. // Clip plane
  91999. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  92000. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  92001. }
  92002. if (mustRebind || !this.isFrozen) {
  92003. if (scene.lightsEnabled) {
  92004. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  92005. }
  92006. // View
  92007. this.bindView(effect);
  92008. // Fog
  92009. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  92010. // image processing
  92011. this._imageProcessingConfiguration.bind(this._activeEffect);
  92012. }
  92013. this._uniformBuffer.update();
  92014. this._afterBind(mesh);
  92015. };
  92016. /**
  92017. * Dispose the material.
  92018. * @param forceDisposeEffect Force disposal of the associated effect.
  92019. * @param forceDisposeTextures Force disposal of the associated textures.
  92020. */
  92021. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  92022. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  92023. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  92024. if (forceDisposeTextures) {
  92025. if (this.diffuseTexture) {
  92026. this.diffuseTexture.dispose();
  92027. }
  92028. if (this.reflectionTexture) {
  92029. this.reflectionTexture.dispose();
  92030. }
  92031. }
  92032. this._renderTargets.dispose();
  92033. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  92034. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  92035. }
  92036. _super.prototype.dispose.call(this, forceDisposeEffect);
  92037. };
  92038. /**
  92039. * Clones the material.
  92040. * @param name The cloned name.
  92041. * @returns The cloned material.
  92042. */
  92043. BackgroundMaterial.prototype.clone = function (name) {
  92044. var _this = this;
  92045. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  92046. };
  92047. /**
  92048. * Serializes the current material to its JSON representation.
  92049. * @returns The JSON representation.
  92050. */
  92051. BackgroundMaterial.prototype.serialize = function () {
  92052. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92053. serializationObject.customType = "BABYLON.BackgroundMaterial";
  92054. return serializationObject;
  92055. };
  92056. /**
  92057. * Gets the class name of the material
  92058. * @returns "BackgroundMaterial"
  92059. */
  92060. BackgroundMaterial.prototype.getClassName = function () {
  92061. return "BackgroundMaterial";
  92062. };
  92063. /**
  92064. * Parse a JSON input to create back a background material.
  92065. * @param source The JSON data to parse
  92066. * @param scene The scene to create the parsed material in
  92067. * @param rootUrl The root url of the assets the material depends upon
  92068. * @returns the instantiated BackgroundMaterial.
  92069. */
  92070. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  92071. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  92072. };
  92073. /**
  92074. * Standard reflectance value at parallel view angle.
  92075. */
  92076. BackgroundMaterial.StandardReflectance0 = 0.05;
  92077. /**
  92078. * Standard reflectance value at grazing angle.
  92079. */
  92080. BackgroundMaterial.StandardReflectance90 = 0.5;
  92081. __decorate([
  92082. BABYLON.serializeAsColor3()
  92083. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  92084. __decorate([
  92085. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92086. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  92087. __decorate([
  92088. BABYLON.serialize()
  92089. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  92090. __decorate([
  92091. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92092. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  92093. __decorate([
  92094. BABYLON.serializeAsColor3()
  92095. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  92096. __decorate([
  92097. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92098. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  92099. __decorate([
  92100. BABYLON.serialize()
  92101. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  92102. __decorate([
  92103. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92104. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  92105. __decorate([
  92106. BABYLON.serializeAsColor3()
  92107. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  92108. __decorate([
  92109. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92110. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  92111. __decorate([
  92112. BABYLON.serialize()
  92113. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  92114. __decorate([
  92115. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  92116. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  92117. __decorate([
  92118. BABYLON.serializeAsTexture()
  92119. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  92120. __decorate([
  92121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92122. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  92123. __decorate([
  92124. BABYLON.serialize()
  92125. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  92126. __decorate([
  92127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92128. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  92129. __decorate([
  92130. BABYLON.serializeAsTexture()
  92131. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  92132. __decorate([
  92133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92134. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  92135. __decorate([
  92136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92137. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  92138. __decorate([
  92139. BABYLON.serialize()
  92140. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  92141. __decorate([
  92142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92143. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  92144. __decorate([
  92145. BABYLON.serialize()
  92146. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  92147. __decorate([
  92148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92149. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  92150. __decorate([
  92151. BABYLON.serializeAsVector3()
  92152. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  92153. __decorate([
  92154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92155. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  92156. __decorate([
  92157. BABYLON.serialize()
  92158. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  92159. __decorate([
  92160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92161. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  92162. __decorate([
  92163. BABYLON.serialize()
  92164. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  92165. __decorate([
  92166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92167. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  92168. __decorate([
  92169. BABYLON.serialize()
  92170. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  92171. __decorate([
  92172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92173. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  92174. __decorate([
  92175. BABYLON.serialize()
  92176. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  92177. __decorate([
  92178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92179. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  92180. __decorate([
  92181. BABYLON.serialize()
  92182. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  92183. __decorate([
  92184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92185. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  92186. __decorate([
  92187. BABYLON.serialize()
  92188. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  92189. __decorate([
  92190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92191. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  92192. __decorate([
  92193. BABYLON.serialize()
  92194. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  92195. __decorate([
  92196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92197. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  92198. __decorate([
  92199. BABYLON.serialize()
  92200. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  92201. __decorate([
  92202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92203. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  92204. __decorate([
  92205. BABYLON.serialize()
  92206. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  92207. __decorate([
  92208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  92209. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  92210. __decorate([
  92211. BABYLON.serializeAsImageProcessingConfiguration()
  92212. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  92213. return BackgroundMaterial;
  92214. }(BABYLON.PushMaterial));
  92215. BABYLON.BackgroundMaterial = BackgroundMaterial;
  92216. })(BABYLON || (BABYLON = {}));
  92217. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  92218. "use strict";
  92219. var __assign = (this && this.__assign) || Object.assign || function(t) {
  92220. for (var s, i = 1, n = arguments.length; i < n; i++) {
  92221. s = arguments[i];
  92222. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  92223. t[p] = s[p];
  92224. }
  92225. return t;
  92226. };
  92227. var BABYLON;
  92228. (function (BABYLON) {
  92229. /**
  92230. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  92231. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  92232. * It also helps with the default setup of your imageProcessing configuration.
  92233. */
  92234. var EnvironmentHelper = /** @class */ (function () {
  92235. /**
  92236. * constructor
  92237. * @param options
  92238. * @param scene The scene to add the material to
  92239. */
  92240. function EnvironmentHelper(options, scene) {
  92241. var _this = this;
  92242. this._errorHandler = function (message, exception) {
  92243. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  92244. };
  92245. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  92246. this._scene = scene;
  92247. this.onErrorObservable = new BABYLON.Observable();
  92248. this._setupBackground();
  92249. this._setupImageProcessing();
  92250. }
  92251. /**
  92252. * Creates the default options for the helper.
  92253. */
  92254. EnvironmentHelper._getDefaultOptions = function () {
  92255. return {
  92256. createGround: true,
  92257. groundSize: 15,
  92258. groundTexture: this._groundTextureCDNUrl,
  92259. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92260. groundOpacity: 0.9,
  92261. enableGroundShadow: true,
  92262. groundShadowLevel: 0.5,
  92263. enableGroundMirror: false,
  92264. groundMirrorSizeRatio: 0.3,
  92265. groundMirrorBlurKernel: 64,
  92266. groundMirrorAmount: 1,
  92267. groundMirrorFresnelWeight: 1,
  92268. groundMirrorFallOffDistance: 0,
  92269. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  92270. groundYBias: 0.00001,
  92271. createSkybox: true,
  92272. skyboxSize: 20,
  92273. skyboxTexture: this._skyboxTextureCDNUrl,
  92274. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  92275. backgroundYRotation: 0,
  92276. sizeAuto: true,
  92277. rootPosition: BABYLON.Vector3.Zero(),
  92278. setupImageProcessing: true,
  92279. environmentTexture: this._environmentTextureCDNUrl,
  92280. cameraExposure: 0.8,
  92281. cameraContrast: 1.2,
  92282. toneMappingEnabled: true,
  92283. };
  92284. };
  92285. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  92286. /**
  92287. * Gets the root mesh created by the helper.
  92288. */
  92289. get: function () {
  92290. return this._rootMesh;
  92291. },
  92292. enumerable: true,
  92293. configurable: true
  92294. });
  92295. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  92296. /**
  92297. * Gets the skybox created by the helper.
  92298. */
  92299. get: function () {
  92300. return this._skybox;
  92301. },
  92302. enumerable: true,
  92303. configurable: true
  92304. });
  92305. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  92306. /**
  92307. * Gets the skybox texture created by the helper.
  92308. */
  92309. get: function () {
  92310. return this._skyboxTexture;
  92311. },
  92312. enumerable: true,
  92313. configurable: true
  92314. });
  92315. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  92316. /**
  92317. * Gets the skybox material created by the helper.
  92318. */
  92319. get: function () {
  92320. return this._skyboxMaterial;
  92321. },
  92322. enumerable: true,
  92323. configurable: true
  92324. });
  92325. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  92326. /**
  92327. * Gets the ground mesh created by the helper.
  92328. */
  92329. get: function () {
  92330. return this._ground;
  92331. },
  92332. enumerable: true,
  92333. configurable: true
  92334. });
  92335. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  92336. /**
  92337. * Gets the ground texture created by the helper.
  92338. */
  92339. get: function () {
  92340. return this._groundTexture;
  92341. },
  92342. enumerable: true,
  92343. configurable: true
  92344. });
  92345. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  92346. /**
  92347. * Gets the ground mirror created by the helper.
  92348. */
  92349. get: function () {
  92350. return this._groundMirror;
  92351. },
  92352. enumerable: true,
  92353. configurable: true
  92354. });
  92355. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  92356. /**
  92357. * Gets the ground mirror render list to helps pushing the meshes
  92358. * you wish in the ground reflection.
  92359. */
  92360. get: function () {
  92361. if (this._groundMirror) {
  92362. return this._groundMirror.renderList;
  92363. }
  92364. return null;
  92365. },
  92366. enumerable: true,
  92367. configurable: true
  92368. });
  92369. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  92370. /**
  92371. * Gets the ground material created by the helper.
  92372. */
  92373. get: function () {
  92374. return this._groundMaterial;
  92375. },
  92376. enumerable: true,
  92377. configurable: true
  92378. });
  92379. /**
  92380. * Updates the background according to the new options
  92381. * @param options
  92382. */
  92383. EnvironmentHelper.prototype.updateOptions = function (options) {
  92384. var newOptions = __assign({}, this._options, options);
  92385. if (this._ground && !newOptions.createGround) {
  92386. this._ground.dispose();
  92387. this._ground = null;
  92388. }
  92389. if (this._groundMaterial && !newOptions.createGround) {
  92390. this._groundMaterial.dispose();
  92391. this._groundMaterial = null;
  92392. }
  92393. if (this._groundTexture) {
  92394. if (this._options.groundTexture != newOptions.groundTexture) {
  92395. this._groundTexture.dispose();
  92396. this._groundTexture = null;
  92397. }
  92398. }
  92399. if (this._skybox && !newOptions.createSkybox) {
  92400. this._skybox.dispose();
  92401. this._skybox = null;
  92402. }
  92403. if (this._skyboxMaterial && !newOptions.createSkybox) {
  92404. this._skyboxMaterial.dispose();
  92405. this._skyboxMaterial = null;
  92406. }
  92407. if (this._skyboxTexture) {
  92408. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  92409. this._skyboxTexture.dispose();
  92410. this._skyboxTexture = null;
  92411. }
  92412. }
  92413. if (this._groundMirror && !newOptions.enableGroundMirror) {
  92414. this._groundMirror.dispose();
  92415. this._groundMirror = null;
  92416. }
  92417. if (this._scene.environmentTexture) {
  92418. if (this._options.environmentTexture != newOptions.environmentTexture) {
  92419. this._scene.environmentTexture.dispose();
  92420. }
  92421. }
  92422. this._options = newOptions;
  92423. this._setupBackground();
  92424. this._setupImageProcessing();
  92425. };
  92426. /**
  92427. * Sets the primary color of all the available elements.
  92428. * @param color
  92429. */
  92430. EnvironmentHelper.prototype.setMainColor = function (color) {
  92431. if (this.groundMaterial) {
  92432. this.groundMaterial.primaryColor = color;
  92433. }
  92434. if (this.skyboxMaterial) {
  92435. this.skyboxMaterial.primaryColor = color;
  92436. }
  92437. if (this.groundMirror) {
  92438. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  92439. }
  92440. };
  92441. /**
  92442. * Setup the image processing according to the specified options.
  92443. */
  92444. EnvironmentHelper.prototype._setupImageProcessing = function () {
  92445. if (this._options.setupImageProcessing) {
  92446. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  92447. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  92448. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  92449. this._setupEnvironmentTexture();
  92450. }
  92451. };
  92452. /**
  92453. * Setup the environment texture according to the specified options.
  92454. */
  92455. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  92456. if (this._scene.environmentTexture) {
  92457. return;
  92458. }
  92459. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  92460. this._scene.environmentTexture = this._options.environmentTexture;
  92461. return;
  92462. }
  92463. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  92464. this._scene.environmentTexture = environmentTexture;
  92465. };
  92466. /**
  92467. * Setup the background according to the specified options.
  92468. */
  92469. EnvironmentHelper.prototype._setupBackground = function () {
  92470. if (!this._rootMesh) {
  92471. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  92472. }
  92473. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  92474. var sceneSize = this._getSceneSize();
  92475. if (this._options.createGround) {
  92476. this._setupGround(sceneSize);
  92477. this._setupGroundMaterial();
  92478. this._setupGroundDiffuseTexture();
  92479. if (this._options.enableGroundMirror) {
  92480. this._setupGroundMirrorTexture(sceneSize);
  92481. }
  92482. this._setupMirrorInGroundMaterial();
  92483. }
  92484. if (this._options.createSkybox) {
  92485. this._setupSkybox(sceneSize);
  92486. this._setupSkyboxMaterial();
  92487. this._setupSkyboxReflectionTexture();
  92488. }
  92489. this._rootMesh.position.x = sceneSize.rootPosition.x;
  92490. this._rootMesh.position.z = sceneSize.rootPosition.z;
  92491. this._rootMesh.position.y = sceneSize.rootPosition.y;
  92492. };
  92493. /**
  92494. * Get the scene sizes according to the setup.
  92495. */
  92496. EnvironmentHelper.prototype._getSceneSize = function () {
  92497. var _this = this;
  92498. var groundSize = this._options.groundSize;
  92499. var skyboxSize = this._options.skyboxSize;
  92500. var rootPosition = this._options.rootPosition;
  92501. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  92502. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92503. }
  92504. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  92505. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  92506. });
  92507. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  92508. if (this._options.sizeAuto) {
  92509. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  92510. this._scene.activeCamera.upperRadiusLimit) {
  92511. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  92512. skyboxSize = groundSize;
  92513. }
  92514. var sceneDiagonalLenght = sceneDiagonal.length();
  92515. if (sceneDiagonalLenght > groundSize) {
  92516. groundSize = sceneDiagonalLenght * 2;
  92517. skyboxSize = groundSize;
  92518. }
  92519. // 10 % bigger.
  92520. groundSize *= 1.1;
  92521. skyboxSize *= 1.5;
  92522. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  92523. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  92524. }
  92525. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  92526. };
  92527. /**
  92528. * Setup the ground according to the specified options.
  92529. */
  92530. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  92531. var _this = this;
  92532. if (!this._ground) {
  92533. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  92534. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  92535. this._ground.parent = this._rootMesh;
  92536. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  92537. }
  92538. this._ground.receiveShadows = this._options.enableGroundShadow;
  92539. };
  92540. /**
  92541. * Setup the ground material according to the specified options.
  92542. */
  92543. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  92544. if (!this._groundMaterial) {
  92545. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  92546. }
  92547. this._groundMaterial.alpha = this._options.groundOpacity;
  92548. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92549. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92550. this._groundMaterial.primaryLevel = 1;
  92551. this._groundMaterial.primaryColor = this._options.groundColor;
  92552. this._groundMaterial.secondaryLevel = 0;
  92553. this._groundMaterial.tertiaryLevel = 0;
  92554. this._groundMaterial.useRGBColor = false;
  92555. this._groundMaterial.enableNoise = true;
  92556. if (this._ground) {
  92557. this._ground.material = this._groundMaterial;
  92558. }
  92559. };
  92560. /**
  92561. * Setup the ground diffuse texture according to the specified options.
  92562. */
  92563. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92564. if (!this._groundMaterial) {
  92565. return;
  92566. }
  92567. if (this._groundTexture) {
  92568. return;
  92569. }
  92570. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92571. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92572. return;
  92573. }
  92574. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92575. diffuseTexture.gammaSpace = false;
  92576. diffuseTexture.hasAlpha = true;
  92577. this._groundMaterial.diffuseTexture = diffuseTexture;
  92578. };
  92579. /**
  92580. * Setup the ground mirror texture according to the specified options.
  92581. */
  92582. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92583. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92584. if (!this._groundMirror) {
  92585. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92586. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92587. this._groundMirror.anisotropicFilteringLevel = 1;
  92588. this._groundMirror.wrapU = wrapping;
  92589. this._groundMirror.wrapV = wrapping;
  92590. this._groundMirror.gammaSpace = false;
  92591. if (this._groundMirror.renderList) {
  92592. for (var i = 0; i < this._scene.meshes.length; i++) {
  92593. var mesh = this._scene.meshes[i];
  92594. if (mesh !== this._ground &&
  92595. mesh !== this._skybox &&
  92596. mesh !== this._rootMesh) {
  92597. this._groundMirror.renderList.push(mesh);
  92598. }
  92599. }
  92600. }
  92601. }
  92602. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92603. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92604. };
  92605. /**
  92606. * Setup the ground to receive the mirror texture.
  92607. */
  92608. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92609. if (this._groundMaterial) {
  92610. this._groundMaterial.reflectionTexture = this._groundMirror;
  92611. this._groundMaterial.reflectionFresnel = true;
  92612. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92613. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92614. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92615. }
  92616. };
  92617. /**
  92618. * Setup the skybox according to the specified options.
  92619. */
  92620. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92621. var _this = this;
  92622. if (!this._skybox) {
  92623. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92624. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92625. }
  92626. this._skybox.parent = this._rootMesh;
  92627. };
  92628. /**
  92629. * Setup the skybox material according to the specified options.
  92630. */
  92631. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92632. if (!this._skybox) {
  92633. return;
  92634. }
  92635. if (!this._skyboxMaterial) {
  92636. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92637. }
  92638. this._skyboxMaterial.useRGBColor = false;
  92639. this._skyboxMaterial.primaryLevel = 1;
  92640. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92641. this._skyboxMaterial.secondaryLevel = 0;
  92642. this._skyboxMaterial.tertiaryLevel = 0;
  92643. this._skyboxMaterial.enableNoise = true;
  92644. this._skybox.material = this._skyboxMaterial;
  92645. };
  92646. /**
  92647. * Setup the skybox reflection texture according to the specified options.
  92648. */
  92649. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92650. if (!this._skyboxMaterial) {
  92651. return;
  92652. }
  92653. if (this._skyboxTexture) {
  92654. return;
  92655. }
  92656. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92657. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92658. return;
  92659. }
  92660. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92661. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92662. this._skyboxTexture.gammaSpace = false;
  92663. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92664. };
  92665. /**
  92666. * Dispose all the elements created by the Helper.
  92667. */
  92668. EnvironmentHelper.prototype.dispose = function () {
  92669. if (this._groundMaterial) {
  92670. this._groundMaterial.dispose(true, true);
  92671. }
  92672. if (this._skyboxMaterial) {
  92673. this._skyboxMaterial.dispose(true, true);
  92674. }
  92675. this._rootMesh.dispose(false);
  92676. };
  92677. /**
  92678. * Default ground texture URL.
  92679. */
  92680. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92681. /**
  92682. * Default skybox texture URL.
  92683. */
  92684. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92685. /**
  92686. * Default environment texture URL.
  92687. */
  92688. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92689. return EnvironmentHelper;
  92690. }());
  92691. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92692. })(BABYLON || (BABYLON = {}));
  92693. //# sourceMappingURL=babylon.environmentHelper.js.map
  92694. "use strict";
  92695. var BABYLON;
  92696. (function (BABYLON) {
  92697. /**
  92698. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92699. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92700. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92701. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92702. */
  92703. var VideoDome = /** @class */ (function (_super) {
  92704. __extends(VideoDome, _super);
  92705. /**
  92706. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92707. * @param name Element's name, child elements will append suffixes for their own names.
  92708. * @param urlsOrVideo
  92709. * @param options An object containing optional or exposed sub element properties:
  92710. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92711. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92712. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92713. * @param options **loop=true** Automatically loop video on end.
  92714. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92715. */
  92716. function VideoDome(name, urlsOrVideo, options, scene) {
  92717. var _this = _super.call(this, name, scene) || this;
  92718. // set defaults and manage values
  92719. name = name || "videoDome";
  92720. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92721. options.clickToPlay = Boolean(options.clickToPlay);
  92722. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92723. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92724. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92725. // create
  92726. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92727. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92728. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92729. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92730. flat: false,
  92731. radius: options.size,
  92732. subdivisions: options.resolution,
  92733. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92734. }, scene);
  92735. // configure material
  92736. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92737. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92738. material.reflectionTexture = _this._videoTexture;
  92739. material.useEquirectangularFOV = true;
  92740. material.fovMultiplier = 1.0;
  92741. // configure mesh
  92742. _this._mesh.material = material;
  92743. _this._mesh.parent = _this;
  92744. // optional configuration
  92745. if (options.clickToPlay) {
  92746. scene.onPointerUp = function () {
  92747. _this._videoTexture.video.play();
  92748. };
  92749. }
  92750. return _this;
  92751. }
  92752. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92753. /**
  92754. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92755. * Also see the options.resolution property.
  92756. */
  92757. get: function () {
  92758. return this._material.fovMultiplier;
  92759. },
  92760. set: function (value) {
  92761. this._material.fovMultiplier = value;
  92762. },
  92763. enumerable: true,
  92764. configurable: true
  92765. });
  92766. /**
  92767. * Releases resources associated with this node.
  92768. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92769. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92770. */
  92771. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92772. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92773. this._videoTexture.dispose();
  92774. this._mesh.dispose();
  92775. this._material.dispose();
  92776. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92777. };
  92778. return VideoDome;
  92779. }(BABYLON.Node));
  92780. BABYLON.VideoDome = VideoDome;
  92781. })(BABYLON || (BABYLON = {}));
  92782. //# sourceMappingURL=babylon.videoDome.js.map
  92783. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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)\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#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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\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{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\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;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,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\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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"};
  92784. 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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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,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,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,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)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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);
  92785. globalObject["BABYLON"] = BABYLON;
  92786. 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 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 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 Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var 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 JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  92787. 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,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,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,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,JoystickAxis ,SimplificationType ,AssetTaskState };